File: | llvm/lib/Bitcode/Reader/BitcodeReader.cpp |
Warning: | line 2618, column 37 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// | ||||
2 | // | ||||
3 | // 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 | ||||
6 | // | ||||
7 | //===----------------------------------------------------------------------===// | ||||
8 | |||||
9 | #include "llvm/Bitcode/BitcodeReader.h" | ||||
10 | #include "MetadataLoader.h" | ||||
11 | #include "ValueList.h" | ||||
12 | #include "llvm/ADT/APFloat.h" | ||||
13 | #include "llvm/ADT/APInt.h" | ||||
14 | #include "llvm/ADT/ArrayRef.h" | ||||
15 | #include "llvm/ADT/DenseMap.h" | ||||
16 | #include "llvm/ADT/Optional.h" | ||||
17 | #include "llvm/ADT/STLExtras.h" | ||||
18 | #include "llvm/ADT/SmallString.h" | ||||
19 | #include "llvm/ADT/SmallVector.h" | ||||
20 | #include "llvm/ADT/StringRef.h" | ||||
21 | #include "llvm/ADT/Triple.h" | ||||
22 | #include "llvm/ADT/Twine.h" | ||||
23 | #include "llvm/Bitstream/BitstreamReader.h" | ||||
24 | #include "llvm/Bitcode/LLVMBitCodes.h" | ||||
25 | #include "llvm/Config/llvm-config.h" | ||||
26 | #include "llvm/IR/Argument.h" | ||||
27 | #include "llvm/IR/Attributes.h" | ||||
28 | #include "llvm/IR/AutoUpgrade.h" | ||||
29 | #include "llvm/IR/BasicBlock.h" | ||||
30 | #include "llvm/IR/CallSite.h" | ||||
31 | #include "llvm/IR/CallingConv.h" | ||||
32 | #include "llvm/IR/Comdat.h" | ||||
33 | #include "llvm/IR/Constant.h" | ||||
34 | #include "llvm/IR/Constants.h" | ||||
35 | #include "llvm/IR/DataLayout.h" | ||||
36 | #include "llvm/IR/DebugInfo.h" | ||||
37 | #include "llvm/IR/DebugInfoMetadata.h" | ||||
38 | #include "llvm/IR/DebugLoc.h" | ||||
39 | #include "llvm/IR/DerivedTypes.h" | ||||
40 | #include "llvm/IR/Function.h" | ||||
41 | #include "llvm/IR/GVMaterializer.h" | ||||
42 | #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" | ||||
48 | #include "llvm/IR/InlineAsm.h" | ||||
49 | #include "llvm/IR/InstIterator.h" | ||||
50 | #include "llvm/IR/InstrTypes.h" | ||||
51 | #include "llvm/IR/Instruction.h" | ||||
52 | #include "llvm/IR/Instructions.h" | ||||
53 | #include "llvm/IR/Intrinsics.h" | ||||
54 | #include "llvm/IR/LLVMContext.h" | ||||
55 | #include "llvm/IR/Metadata.h" | ||||
56 | #include "llvm/IR/Module.h" | ||||
57 | #include "llvm/IR/ModuleSummaryIndex.h" | ||||
58 | #include "llvm/IR/Operator.h" | ||||
59 | #include "llvm/IR/Type.h" | ||||
60 | #include "llvm/IR/Value.h" | ||||
61 | #include "llvm/IR/Verifier.h" | ||||
62 | #include "llvm/Support/AtomicOrdering.h" | ||||
63 | #include "llvm/Support/Casting.h" | ||||
64 | #include "llvm/Support/CommandLine.h" | ||||
65 | #include "llvm/Support/Compiler.h" | ||||
66 | #include "llvm/Support/Debug.h" | ||||
67 | #include "llvm/Support/Error.h" | ||||
68 | #include "llvm/Support/ErrorHandling.h" | ||||
69 | #include "llvm/Support/ErrorOr.h" | ||||
70 | #include "llvm/Support/ManagedStatic.h" | ||||
71 | #include "llvm/Support/MathExtras.h" | ||||
72 | #include "llvm/Support/MemoryBuffer.h" | ||||
73 | #include "llvm/Support/raw_ostream.h" | ||||
74 | #include <algorithm> | ||||
75 | #include <cassert> | ||||
76 | #include <cstddef> | ||||
77 | #include <cstdint> | ||||
78 | #include <deque> | ||||
79 | #include <map> | ||||
80 | #include <memory> | ||||
81 | #include <set> | ||||
82 | #include <string> | ||||
83 | #include <system_error> | ||||
84 | #include <tuple> | ||||
85 | #include <utility> | ||||
86 | #include <vector> | ||||
87 | |||||
88 | using namespace llvm; | ||||
89 | |||||
90 | static 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 | |||||
95 | namespace { | ||||
96 | |||||
97 | enum { | ||||
98 | SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex | ||||
99 | }; | ||||
100 | |||||
101 | } // end anonymous namespace | ||||
102 | |||||
103 | static Error error(const Twine &Message) { | ||||
104 | return make_error<StringError>( | ||||
105 | Message, make_error_code(BitcodeError::CorruptedBitcode)); | ||||
106 | } | ||||
107 | |||||
108 | static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) { | ||||
109 | if (!Stream.canSkipToPos(4)) | ||||
110 | return createStringError(std::errc::illegal_byte_sequence, | ||||
111 | "file too small to contain bitcode header"); | ||||
112 | for (unsigned C : {'B', 'C'}) | ||||
113 | if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { | ||||
114 | if (Res.get() != C) | ||||
115 | return createStringError(std::errc::illegal_byte_sequence, | ||||
116 | "file doesn't start with bitcode header"); | ||||
117 | } else | ||||
118 | return Res.takeError(); | ||||
119 | for (unsigned C : {0x0, 0xC, 0xE, 0xD}) | ||||
120 | if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) { | ||||
121 | if (Res.get() != C) | ||||
122 | return createStringError(std::errc::illegal_byte_sequence, | ||||
123 | "file doesn't start with bitcode header"); | ||||
124 | } else | ||||
125 | return Res.takeError(); | ||||
126 | return Error::success(); | ||||
127 | } | ||||
128 | |||||
129 | static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) { | ||||
130 | const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart(); | ||||
131 | const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize(); | ||||
132 | |||||
133 | if (Buffer.getBufferSize() & 3) | ||||
134 | return error("Invalid bitcode signature"); | ||||
135 | |||||
136 | // If we have a wrapper header, parse it and ignore the non-bc file contents. | ||||
137 | // The magic number is 0x0B17C0DE stored in little endian. | ||||
138 | if (isBitcodeWrapper(BufPtr, BufEnd)) | ||||
139 | if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) | ||||
140 | return error("Invalid bitcode wrapper header"); | ||||
141 | |||||
142 | BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd)); | ||||
143 | if (Error Err = hasInvalidBitcodeHeader(Stream)) | ||||
144 | return std::move(Err); | ||||
145 | |||||
146 | return std::move(Stream); | ||||
147 | } | ||||
148 | |||||
149 | /// Convert a string from a record into an std::string, return true on failure. | ||||
150 | template <typename StrTy> | ||||
151 | static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, | ||||
152 | StrTy &Result) { | ||||
153 | if (Idx > Record.size()) | ||||
154 | return true; | ||||
155 | |||||
156 | for (unsigned i = Idx, e = Record.size(); i != e; ++i) | ||||
157 | Result += (char)Record[i]; | ||||
158 | return false; | ||||
159 | } | ||||
160 | |||||
161 | // Strip all the TBAA attachment for the module. | ||||
162 | static void stripTBAA(Module *M) { | ||||
163 | for (auto &F : *M) { | ||||
164 | if (F.isMaterializable()) | ||||
165 | continue; | ||||
166 | for (auto &I : instructions(F)) | ||||
167 | I.setMetadata(LLVMContext::MD_tbaa, nullptr); | ||||
168 | } | ||||
169 | } | ||||
170 | |||||
171 | /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the | ||||
172 | /// "epoch" encoded in the bitcode, and return the producer name if any. | ||||
173 | static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) { | ||||
174 | if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) | ||||
175 | return std::move(Err); | ||||
176 | |||||
177 | // Read all the records. | ||||
178 | SmallVector<uint64_t, 64> Record; | ||||
179 | |||||
180 | std::string ProducerIdentification; | ||||
181 | |||||
182 | while (true) { | ||||
183 | BitstreamEntry Entry; | ||||
184 | if (Expected<BitstreamEntry> Res = Stream.advance()) | ||||
185 | Entry = Res.get(); | ||||
186 | else | ||||
187 | return Res.takeError(); | ||||
188 | |||||
189 | switch (Entry.Kind) { | ||||
190 | default: | ||||
191 | case BitstreamEntry::Error: | ||||
192 | return error("Malformed block"); | ||||
193 | case BitstreamEntry::EndBlock: | ||||
194 | return ProducerIdentification; | ||||
195 | case BitstreamEntry::Record: | ||||
196 | // The interesting case. | ||||
197 | break; | ||||
198 | } | ||||
199 | |||||
200 | // Read a record. | ||||
201 | Record.clear(); | ||||
202 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
203 | if (!MaybeBitCode) | ||||
204 | return MaybeBitCode.takeError(); | ||||
205 | switch (MaybeBitCode.get()) { | ||||
206 | default: // Default behavior: reject | ||||
207 | return error("Invalid value"); | ||||
208 | case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N] | ||||
209 | convertToString(Record, 0, ProducerIdentification); | ||||
210 | break; | ||||
211 | case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] | ||||
212 | unsigned epoch = (unsigned)Record[0]; | ||||
213 | if (epoch != bitc::BITCODE_CURRENT_EPOCH) { | ||||
214 | return error( | ||||
215 | Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + | ||||
216 | "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); | ||||
217 | } | ||||
218 | } | ||||
219 | } | ||||
220 | } | ||||
221 | } | ||||
222 | |||||
223 | static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) { | ||||
224 | // We expect a number of well-defined blocks, though we don't necessarily | ||||
225 | // need to understand them all. | ||||
226 | while (true) { | ||||
227 | if (Stream.AtEndOfStream()) | ||||
228 | return ""; | ||||
229 | |||||
230 | BitstreamEntry Entry; | ||||
231 | if (Expected<BitstreamEntry> Res = Stream.advance()) | ||||
232 | Entry = std::move(Res.get()); | ||||
233 | else | ||||
234 | return Res.takeError(); | ||||
235 | |||||
236 | switch (Entry.Kind) { | ||||
237 | case BitstreamEntry::EndBlock: | ||||
238 | case BitstreamEntry::Error: | ||||
239 | return error("Malformed block"); | ||||
240 | |||||
241 | case BitstreamEntry::SubBlock: | ||||
242 | if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) | ||||
243 | return readIdentificationBlock(Stream); | ||||
244 | |||||
245 | // Ignore other sub-blocks. | ||||
246 | if (Error Err = Stream.SkipBlock()) | ||||
247 | return std::move(Err); | ||||
248 | continue; | ||||
249 | case BitstreamEntry::Record: | ||||
250 | if (Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID)) | ||||
251 | continue; | ||||
252 | else | ||||
253 | return Skipped.takeError(); | ||||
254 | } | ||||
255 | } | ||||
256 | } | ||||
257 | |||||
258 | static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) { | ||||
259 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) | ||||
260 | return std::move(Err); | ||||
261 | |||||
262 | SmallVector<uint64_t, 64> Record; | ||||
263 | // Read all the records for this module. | ||||
264 | |||||
265 | while (true) { | ||||
266 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
267 | if (!MaybeEntry) | ||||
268 | return MaybeEntry.takeError(); | ||||
269 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
270 | |||||
271 | switch (Entry.Kind) { | ||||
272 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
273 | case BitstreamEntry::Error: | ||||
274 | return error("Malformed block"); | ||||
275 | case BitstreamEntry::EndBlock: | ||||
276 | return false; | ||||
277 | case BitstreamEntry::Record: | ||||
278 | // The interesting case. | ||||
279 | break; | ||||
280 | } | ||||
281 | |||||
282 | // Read a record. | ||||
283 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
284 | if (!MaybeRecord) | ||||
285 | return MaybeRecord.takeError(); | ||||
286 | switch (MaybeRecord.get()) { | ||||
287 | default: | ||||
288 | break; // Default behavior, ignore unknown content. | ||||
289 | case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] | ||||
290 | std::string S; | ||||
291 | if (convertToString(Record, 0, S)) | ||||
292 | return error("Invalid record"); | ||||
293 | // Check for the i386 and other (x86_64, ARM) conventions | ||||
294 | if (S.find("__DATA,__objc_catlist") != std::string::npos || | ||||
295 | S.find("__OBJC,__category") != std::string::npos) | ||||
296 | return true; | ||||
297 | break; | ||||
298 | } | ||||
299 | } | ||||
300 | Record.clear(); | ||||
301 | } | ||||
302 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 302); | ||||
303 | } | ||||
304 | |||||
305 | static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) { | ||||
306 | // We expect a number of well-defined blocks, though we don't necessarily | ||||
307 | // need to understand them all. | ||||
308 | while (true) { | ||||
309 | BitstreamEntry Entry; | ||||
310 | if (Expected<BitstreamEntry> Res = Stream.advance()) | ||||
311 | Entry = std::move(Res.get()); | ||||
312 | else | ||||
313 | return Res.takeError(); | ||||
314 | |||||
315 | switch (Entry.Kind) { | ||||
316 | case BitstreamEntry::Error: | ||||
317 | return error("Malformed block"); | ||||
318 | case BitstreamEntry::EndBlock: | ||||
319 | return false; | ||||
320 | |||||
321 | case BitstreamEntry::SubBlock: | ||||
322 | if (Entry.ID == bitc::MODULE_BLOCK_ID) | ||||
323 | return hasObjCCategoryInModule(Stream); | ||||
324 | |||||
325 | // Ignore other sub-blocks. | ||||
326 | if (Error Err = Stream.SkipBlock()) | ||||
327 | return std::move(Err); | ||||
328 | continue; | ||||
329 | |||||
330 | case BitstreamEntry::Record: | ||||
331 | if (Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID)) | ||||
332 | continue; | ||||
333 | else | ||||
334 | return Skipped.takeError(); | ||||
335 | } | ||||
336 | } | ||||
337 | } | ||||
338 | |||||
339 | static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) { | ||||
340 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) | ||||
341 | return std::move(Err); | ||||
342 | |||||
343 | SmallVector<uint64_t, 64> Record; | ||||
344 | |||||
345 | std::string Triple; | ||||
346 | |||||
347 | // Read all the records for this module. | ||||
348 | while (true) { | ||||
349 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
350 | if (!MaybeEntry) | ||||
351 | return MaybeEntry.takeError(); | ||||
352 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
353 | |||||
354 | switch (Entry.Kind) { | ||||
355 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
356 | case BitstreamEntry::Error: | ||||
357 | return error("Malformed block"); | ||||
358 | case BitstreamEntry::EndBlock: | ||||
359 | return Triple; | ||||
360 | case BitstreamEntry::Record: | ||||
361 | // The interesting case. | ||||
362 | break; | ||||
363 | } | ||||
364 | |||||
365 | // Read a record. | ||||
366 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
367 | if (!MaybeRecord) | ||||
368 | return MaybeRecord.takeError(); | ||||
369 | switch (MaybeRecord.get()) { | ||||
370 | default: break; // Default behavior, ignore unknown content. | ||||
371 | case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] | ||||
372 | std::string S; | ||||
373 | if (convertToString(Record, 0, S)) | ||||
374 | return error("Invalid record"); | ||||
375 | Triple = S; | ||||
376 | break; | ||||
377 | } | ||||
378 | } | ||||
379 | Record.clear(); | ||||
380 | } | ||||
381 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 381); | ||||
382 | } | ||||
383 | |||||
384 | static Expected<std::string> readTriple(BitstreamCursor &Stream) { | ||||
385 | // We expect a number of well-defined blocks, though we don't necessarily | ||||
386 | // need to understand them all. | ||||
387 | while (true) { | ||||
388 | Expected<BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
389 | if (!MaybeEntry) | ||||
390 | return MaybeEntry.takeError(); | ||||
391 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
392 | |||||
393 | switch (Entry.Kind) { | ||||
394 | case BitstreamEntry::Error: | ||||
395 | return error("Malformed block"); | ||||
396 | case BitstreamEntry::EndBlock: | ||||
397 | return ""; | ||||
398 | |||||
399 | case BitstreamEntry::SubBlock: | ||||
400 | if (Entry.ID == bitc::MODULE_BLOCK_ID) | ||||
401 | return readModuleTriple(Stream); | ||||
402 | |||||
403 | // Ignore other sub-blocks. | ||||
404 | if (Error Err = Stream.SkipBlock()) | ||||
405 | return std::move(Err); | ||||
406 | continue; | ||||
407 | |||||
408 | case BitstreamEntry::Record: | ||||
409 | if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID)) | ||||
410 | continue; | ||||
411 | else | ||||
412 | return Skipped.takeError(); | ||||
413 | } | ||||
414 | } | ||||
415 | } | ||||
416 | |||||
417 | namespace { | ||||
418 | |||||
419 | class BitcodeReaderBase { | ||||
420 | protected: | ||||
421 | BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab) | ||||
422 | : Stream(std::move(Stream)), Strtab(Strtab) { | ||||
423 | this->Stream.setBlockInfo(&BlockInfo); | ||||
424 | } | ||||
425 | |||||
426 | BitstreamBlockInfo BlockInfo; | ||||
427 | BitstreamCursor Stream; | ||||
428 | StringRef Strtab; | ||||
429 | |||||
430 | /// In version 2 of the bitcode we store names of global values and comdats in | ||||
431 | /// a string table rather than in the VST. | ||||
432 | bool UseStrtab = false; | ||||
433 | |||||
434 | Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record); | ||||
435 | |||||
436 | /// If this module uses a string table, pop the reference to the string table | ||||
437 | /// and return the referenced string and the rest of the record. Otherwise | ||||
438 | /// just return the record itself. | ||||
439 | std::pair<StringRef, ArrayRef<uint64_t>> | ||||
440 | readNameFromStrtab(ArrayRef<uint64_t> Record); | ||||
441 | |||||
442 | bool readBlockInfo(); | ||||
443 | |||||
444 | // Contains an arbitrary and optional string identifying the bitcode producer | ||||
445 | std::string ProducerIdentification; | ||||
446 | |||||
447 | Error error(const Twine &Message); | ||||
448 | }; | ||||
449 | |||||
450 | } // end anonymous namespace | ||||
451 | |||||
452 | Error BitcodeReaderBase::error(const Twine &Message) { | ||||
453 | std::string FullMsg = Message.str(); | ||||
454 | if (!ProducerIdentification.empty()) | ||||
455 | FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " + | ||||
456 | LLVM_VERSION_STRING"11.0.0" "')"; | ||||
457 | return ::error(FullMsg); | ||||
458 | } | ||||
459 | |||||
460 | Expected<unsigned> | ||||
461 | BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) { | ||||
462 | if (Record.empty()) | ||||
463 | return error("Invalid record"); | ||||
464 | unsigned ModuleVersion = Record[0]; | ||||
465 | if (ModuleVersion > 2) | ||||
466 | return error("Invalid value"); | ||||
467 | UseStrtab = ModuleVersion >= 2; | ||||
468 | return ModuleVersion; | ||||
469 | } | ||||
470 | |||||
471 | std::pair<StringRef, ArrayRef<uint64_t>> | ||||
472 | BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) { | ||||
473 | if (!UseStrtab) | ||||
474 | return {"", Record}; | ||||
475 | // Invalid reference. Let the caller complain about the record being empty. | ||||
476 | if (Record[0] + Record[1] > Strtab.size()) | ||||
477 | return {"", {}}; | ||||
478 | return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)}; | ||||
479 | } | ||||
480 | |||||
481 | namespace { | ||||
482 | |||||
483 | class BitcodeReader : public BitcodeReaderBase, public GVMaterializer { | ||||
484 | LLVMContext &Context; | ||||
485 | Module *TheModule = nullptr; | ||||
486 | // Next offset to start scanning for lazy parsing of function bodies. | ||||
487 | uint64_t NextUnreadBit = 0; | ||||
488 | // Last function offset found in the VST. | ||||
489 | uint64_t LastFunctionBlockBit = 0; | ||||
490 | bool SeenValueSymbolTable = false; | ||||
491 | uint64_t VSTOffset = 0; | ||||
492 | |||||
493 | std::vector<std::string> SectionTable; | ||||
494 | std::vector<std::string> GCTable; | ||||
495 | |||||
496 | std::vector<Type*> TypeList; | ||||
497 | DenseMap<Function *, FunctionType *> FunctionTypes; | ||||
498 | BitcodeReaderValueList ValueList; | ||||
499 | Optional<MetadataLoader> MDLoader; | ||||
500 | std::vector<Comdat *> ComdatList; | ||||
501 | SmallVector<Instruction *, 64> InstructionList; | ||||
502 | |||||
503 | std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits; | ||||
504 | std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits; | ||||
505 | std::vector<std::pair<Function *, unsigned>> FunctionPrefixes; | ||||
506 | std::vector<std::pair<Function *, unsigned>> FunctionPrologues; | ||||
507 | std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns; | ||||
508 | |||||
509 | /// The set of attributes by index. Index zero in the file is for null, and | ||||
510 | /// is thus not represented here. As such all indices are off by one. | ||||
511 | std::vector<AttributeList> MAttributes; | ||||
512 | |||||
513 | /// The set of attribute groups. | ||||
514 | std::map<unsigned, AttributeList> MAttributeGroups; | ||||
515 | |||||
516 | /// While parsing a function body, this is a list of the basic blocks for the | ||||
517 | /// function. | ||||
518 | std::vector<BasicBlock*> FunctionBBs; | ||||
519 | |||||
520 | // When reading the module header, this list is populated with functions that | ||||
521 | // have bodies later in the file. | ||||
522 | std::vector<Function*> FunctionsWithBodies; | ||||
523 | |||||
524 | // When intrinsic functions are encountered which require upgrading they are | ||||
525 | // stored here with their replacement function. | ||||
526 | using UpdatedIntrinsicMap = DenseMap<Function *, Function *>; | ||||
527 | UpdatedIntrinsicMap UpgradedIntrinsics; | ||||
528 | // Intrinsics which were remangled because of types rename | ||||
529 | UpdatedIntrinsicMap RemangledIntrinsics; | ||||
530 | |||||
531 | // Several operations happen after the module header has been read, but | ||||
532 | // before function bodies are processed. This keeps track of whether | ||||
533 | // we've done this yet. | ||||
534 | bool SeenFirstFunctionBody = false; | ||||
535 | |||||
536 | /// When function bodies are initially scanned, this map contains info about | ||||
537 | /// where to find deferred function body in the stream. | ||||
538 | DenseMap<Function*, uint64_t> DeferredFunctionInfo; | ||||
539 | |||||
540 | /// When Metadata block is initially scanned when parsing the module, we may | ||||
541 | /// choose to defer parsing of the metadata. This vector contains info about | ||||
542 | /// which Metadata blocks are deferred. | ||||
543 | std::vector<uint64_t> DeferredMetadataInfo; | ||||
544 | |||||
545 | /// These are basic blocks forward-referenced by block addresses. They are | ||||
546 | /// inserted lazily into functions when they're loaded. The basic block ID is | ||||
547 | /// its index into the vector. | ||||
548 | DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; | ||||
549 | std::deque<Function *> BasicBlockFwdRefQueue; | ||||
550 | |||||
551 | /// Indicates that we are using a new encoding for instruction operands where | ||||
552 | /// most operands in the current FUNCTION_BLOCK are encoded relative to the | ||||
553 | /// instruction number, for a more compact encoding. Some instruction | ||||
554 | /// operands are not relative to the instruction ID: basic block numbers, and | ||||
555 | /// types. Once the old style function blocks have been phased out, we would | ||||
556 | /// not need this flag. | ||||
557 | bool UseRelativeIDs = false; | ||||
558 | |||||
559 | /// True if all functions will be materialized, negating the need to process | ||||
560 | /// (e.g.) blockaddress forward references. | ||||
561 | bool WillMaterializeAllForwardRefs = false; | ||||
562 | |||||
563 | bool StripDebugInfo = false; | ||||
564 | TBAAVerifier TBAAVerifyHelper; | ||||
565 | |||||
566 | std::vector<std::string> BundleTags; | ||||
567 | SmallVector<SyncScope::ID, 8> SSIDs; | ||||
568 | |||||
569 | public: | ||||
570 | BitcodeReader(BitstreamCursor Stream, StringRef Strtab, | ||||
571 | StringRef ProducerIdentification, LLVMContext &Context); | ||||
572 | |||||
573 | Error materializeForwardReferencedFunctions(); | ||||
574 | |||||
575 | Error materialize(GlobalValue *GV) override; | ||||
576 | Error materializeModule() override; | ||||
577 | std::vector<StructType *> getIdentifiedStructTypes() const override; | ||||
578 | |||||
579 | /// Main interface to parsing a bitcode buffer. | ||||
580 | /// \returns true if an error occurred. | ||||
581 | Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false, | ||||
582 | bool IsImporting = false); | ||||
583 | |||||
584 | static uint64_t decodeSignRotatedValue(uint64_t V); | ||||
585 | |||||
586 | /// Materialize any deferred Metadata block. | ||||
587 | Error materializeMetadata() override; | ||||
588 | |||||
589 | void setStripDebugInfo() override; | ||||
590 | |||||
591 | private: | ||||
592 | std::vector<StructType *> IdentifiedStructTypes; | ||||
593 | StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); | ||||
594 | StructType *createIdentifiedStructType(LLVMContext &Context); | ||||
595 | |||||
596 | /// Map all pointer types within \param Ty to the opaque pointer | ||||
597 | /// type in the same address space if opaque pointers are being | ||||
598 | /// used, otherwise nop. This converts a bitcode-reader internal | ||||
599 | /// type into one suitable for use in a Value. | ||||
600 | Type *flattenPointerTypes(Type *Ty) { | ||||
601 | return Ty; | ||||
602 | } | ||||
603 | |||||
604 | /// Given a fully structured pointer type (i.e. not opaque), return | ||||
605 | /// the flattened form of its element, suitable for use in a Value. | ||||
606 | Type *getPointerElementFlatType(Type *Ty) { | ||||
607 | return flattenPointerTypes(cast<PointerType>(Ty)->getElementType()); | ||||
608 | } | ||||
609 | |||||
610 | /// Given a fully structured pointer type, get its element type in | ||||
611 | /// both fully structured form, and flattened form suitable for use | ||||
612 | /// in a Value. | ||||
613 | std::pair<Type *, Type *> getPointerElementTypes(Type *FullTy) { | ||||
614 | Type *ElTy = cast<PointerType>(FullTy)->getElementType(); | ||||
615 | return std::make_pair(ElTy, flattenPointerTypes(ElTy)); | ||||
616 | } | ||||
617 | |||||
618 | /// Return the flattened type (suitable for use in a Value) | ||||
619 | /// specified by the given \param ID . | ||||
620 | Type *getTypeByID(unsigned ID) { | ||||
621 | return flattenPointerTypes(getFullyStructuredTypeByID(ID)); | ||||
622 | } | ||||
623 | |||||
624 | /// Return the fully structured (bitcode-reader internal) type | ||||
625 | /// corresponding to the given \param ID . | ||||
626 | Type *getFullyStructuredTypeByID(unsigned ID); | ||||
627 | |||||
628 | Value *getFnValueByID(unsigned ID, Type *Ty, Type **FullTy = nullptr) { | ||||
629 | if (Ty && Ty->isMetadataTy()) | ||||
630 | return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); | ||||
631 | return ValueList.getValueFwdRef(ID, Ty, FullTy); | ||||
632 | } | ||||
633 | |||||
634 | Metadata *getFnMetadataByID(unsigned ID) { | ||||
635 | return MDLoader->getMetadataFwdRefOrLoad(ID); | ||||
636 | } | ||||
637 | |||||
638 | BasicBlock *getBasicBlock(unsigned ID) const { | ||||
639 | if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID | ||||
640 | return FunctionBBs[ID]; | ||||
641 | } | ||||
642 | |||||
643 | AttributeList getAttributes(unsigned i) const { | ||||
644 | if (i-1 < MAttributes.size()) | ||||
645 | return MAttributes[i-1]; | ||||
646 | return AttributeList(); | ||||
647 | } | ||||
648 | |||||
649 | /// Read a value/type pair out of the specified record from slot 'Slot'. | ||||
650 | /// Increment Slot past the number of slots used in the record. Return true on | ||||
651 | /// failure. | ||||
652 | bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, | ||||
653 | unsigned InstNum, Value *&ResVal, | ||||
654 | Type **FullTy = nullptr) { | ||||
655 | if (Slot == Record.size()) return true; | ||||
656 | unsigned ValNo = (unsigned)Record[Slot++]; | ||||
657 | // Adjust the ValNo, if it was encoded relative to the InstNum. | ||||
658 | if (UseRelativeIDs) | ||||
659 | ValNo = InstNum - ValNo; | ||||
660 | if (ValNo < InstNum) { | ||||
661 | // If this is not a forward reference, just return the value we already | ||||
662 | // have. | ||||
663 | ResVal = getFnValueByID(ValNo, nullptr, FullTy); | ||||
664 | return ResVal == nullptr; | ||||
665 | } | ||||
666 | if (Slot == Record.size()) | ||||
667 | return true; | ||||
668 | |||||
669 | unsigned TypeNo = (unsigned)Record[Slot++]; | ||||
670 | ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo)); | ||||
671 | if (FullTy) | ||||
672 | *FullTy = getFullyStructuredTypeByID(TypeNo); | ||||
673 | return ResVal == nullptr; | ||||
674 | } | ||||
675 | |||||
676 | /// Read a value out of the specified record from slot 'Slot'. Increment Slot | ||||
677 | /// past the number of slots used by the value in the record. Return true if | ||||
678 | /// there is an error. | ||||
679 | bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, | ||||
680 | unsigned InstNum, Type *Ty, Value *&ResVal) { | ||||
681 | if (getValue(Record, Slot, InstNum, Ty, ResVal)) | ||||
682 | return true; | ||||
683 | // All values currently take a single record slot. | ||||
684 | ++Slot; | ||||
685 | return false; | ||||
686 | } | ||||
687 | |||||
688 | /// Like popValue, but does not increment the Slot number. | ||||
689 | bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, | ||||
690 | unsigned InstNum, Type *Ty, Value *&ResVal) { | ||||
691 | ResVal = getValue(Record, Slot, InstNum, Ty); | ||||
692 | return ResVal == nullptr; | ||||
693 | } | ||||
694 | |||||
695 | /// Version of getValue that returns ResVal directly, or 0 if there is an | ||||
696 | /// error. | ||||
697 | Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, | ||||
698 | unsigned InstNum, Type *Ty) { | ||||
699 | if (Slot == Record.size()) return nullptr; | ||||
700 | unsigned ValNo = (unsigned)Record[Slot]; | ||||
701 | // Adjust the ValNo, if it was encoded relative to the InstNum. | ||||
702 | if (UseRelativeIDs) | ||||
703 | ValNo = InstNum - ValNo; | ||||
704 | return getFnValueByID(ValNo, Ty); | ||||
705 | } | ||||
706 | |||||
707 | /// Like getValue, but decodes signed VBRs. | ||||
708 | Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot, | ||||
709 | unsigned InstNum, Type *Ty) { | ||||
710 | if (Slot == Record.size()) return nullptr; | ||||
711 | unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); | ||||
712 | // Adjust the ValNo, if it was encoded relative to the InstNum. | ||||
713 | if (UseRelativeIDs) | ||||
714 | ValNo = InstNum - ValNo; | ||||
715 | return getFnValueByID(ValNo, Ty); | ||||
716 | } | ||||
717 | |||||
718 | /// Upgrades old-style typeless byval attributes by adding the corresponding | ||||
719 | /// argument's pointee type. | ||||
720 | void propagateByValTypes(CallBase *CB, ArrayRef<Type *> ArgsFullTys); | ||||
721 | |||||
722 | /// Converts alignment exponent (i.e. power of two (or zero)) to the | ||||
723 | /// corresponding alignment to use. If alignment is too large, returns | ||||
724 | /// a corresponding error code. | ||||
725 | Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment); | ||||
726 | Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); | ||||
727 | Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false); | ||||
728 | |||||
729 | Error parseComdatRecord(ArrayRef<uint64_t> Record); | ||||
730 | Error parseGlobalVarRecord(ArrayRef<uint64_t> Record); | ||||
731 | Error parseFunctionRecord(ArrayRef<uint64_t> Record); | ||||
732 | Error parseGlobalIndirectSymbolRecord(unsigned BitCode, | ||||
733 | ArrayRef<uint64_t> Record); | ||||
734 | |||||
735 | Error parseAttributeBlock(); | ||||
736 | Error parseAttributeGroupBlock(); | ||||
737 | Error parseTypeTable(); | ||||
738 | Error parseTypeTableBody(); | ||||
739 | Error parseOperandBundleTags(); | ||||
740 | Error parseSyncScopeNames(); | ||||
741 | |||||
742 | Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, | ||||
743 | unsigned NameIndex, Triple &TT); | ||||
744 | void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F, | ||||
745 | ArrayRef<uint64_t> Record); | ||||
746 | Error parseValueSymbolTable(uint64_t Offset = 0); | ||||
747 | Error parseGlobalValueSymbolTable(); | ||||
748 | Error parseConstants(); | ||||
749 | Error rememberAndSkipFunctionBodies(); | ||||
750 | Error rememberAndSkipFunctionBody(); | ||||
751 | /// Save the positions of the Metadata blocks and skip parsing the blocks. | ||||
752 | Error rememberAndSkipMetadata(); | ||||
753 | Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType); | ||||
754 | Error parseFunctionBody(Function *F); | ||||
755 | Error globalCleanup(); | ||||
756 | Error resolveGlobalAndIndirectSymbolInits(); | ||||
757 | Error parseUseLists(); | ||||
758 | Error findFunctionInStream( | ||||
759 | Function *F, | ||||
760 | DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); | ||||
761 | |||||
762 | SyncScope::ID getDecodedSyncScopeID(unsigned Val); | ||||
763 | }; | ||||
764 | |||||
765 | /// Class to manage reading and parsing function summary index bitcode | ||||
766 | /// files/sections. | ||||
767 | class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase { | ||||
768 | /// The module index built during parsing. | ||||
769 | ModuleSummaryIndex &TheIndex; | ||||
770 | |||||
771 | /// Indicates whether we have encountered a global value summary section | ||||
772 | /// yet during parsing. | ||||
773 | bool SeenGlobalValSummary = false; | ||||
774 | |||||
775 | /// Indicates whether we have already parsed the VST, used for error checking. | ||||
776 | bool SeenValueSymbolTable = false; | ||||
777 | |||||
778 | /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. | ||||
779 | /// Used to enable on-demand parsing of the VST. | ||||
780 | uint64_t VSTOffset = 0; | ||||
781 | |||||
782 | // Map to save ValueId to ValueInfo association that was recorded in the | ||||
783 | // ValueSymbolTable. It is used after the VST is parsed to convert | ||||
784 | // call graph edges read from the function summary from referencing | ||||
785 | // callees by their ValueId to using the ValueInfo instead, which is how | ||||
786 | // they are recorded in the summary index being built. | ||||
787 | // We save a GUID which refers to the same global as the ValueInfo, but | ||||
788 | // ignoring the linkage, i.e. for values other than local linkage they are | ||||
789 | // identical. | ||||
790 | DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>> | ||||
791 | ValueIdToValueInfoMap; | ||||
792 | |||||
793 | /// Map populated during module path string table parsing, from the | ||||
794 | /// module ID to a string reference owned by the index's module | ||||
795 | /// path string table, used to correlate with combined index | ||||
796 | /// summary records. | ||||
797 | DenseMap<uint64_t, StringRef> ModuleIdMap; | ||||
798 | |||||
799 | /// Original source file name recorded in a bitcode record. | ||||
800 | std::string SourceFileName; | ||||
801 | |||||
802 | /// The string identifier given to this module by the client, normally the | ||||
803 | /// path to the bitcode file. | ||||
804 | StringRef ModulePath; | ||||
805 | |||||
806 | /// For per-module summary indexes, the unique numerical identifier given to | ||||
807 | /// this module by the client. | ||||
808 | unsigned ModuleId; | ||||
809 | |||||
810 | public: | ||||
811 | ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab, | ||||
812 | ModuleSummaryIndex &TheIndex, | ||||
813 | StringRef ModulePath, unsigned ModuleId); | ||||
814 | |||||
815 | Error parseModule(); | ||||
816 | |||||
817 | private: | ||||
818 | void setValueGUID(uint64_t ValueID, StringRef ValueName, | ||||
819 | GlobalValue::LinkageTypes Linkage, | ||||
820 | StringRef SourceFileName); | ||||
821 | Error parseValueSymbolTable( | ||||
822 | uint64_t Offset, | ||||
823 | DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); | ||||
824 | std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record); | ||||
825 | std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record, | ||||
826 | bool IsOldProfileFormat, | ||||
827 | bool HasProfile, | ||||
828 | bool HasRelBF); | ||||
829 | Error parseEntireSummary(unsigned ID); | ||||
830 | Error parseModuleStringTable(); | ||||
831 | void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record); | ||||
832 | void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot, | ||||
833 | TypeIdCompatibleVtableInfo &TypeId); | ||||
834 | |||||
835 | std::pair<ValueInfo, GlobalValue::GUID> | ||||
836 | getValueInfoFromValueId(unsigned ValueId); | ||||
837 | |||||
838 | void addThisModule(); | ||||
839 | ModuleSummaryIndex::ModuleInfo *getThisModule(); | ||||
840 | }; | ||||
841 | |||||
842 | } // end anonymous namespace | ||||
843 | |||||
844 | std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, | ||||
845 | Error Err) { | ||||
846 | if (Err) { | ||||
847 | std::error_code EC; | ||||
848 | handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { | ||||
849 | EC = EIB.convertToErrorCode(); | ||||
850 | Ctx.emitError(EIB.message()); | ||||
851 | }); | ||||
852 | return EC; | ||||
853 | } | ||||
854 | return std::error_code(); | ||||
855 | } | ||||
856 | |||||
857 | BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab, | ||||
858 | StringRef ProducerIdentification, | ||||
859 | LLVMContext &Context) | ||||
860 | : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context), | ||||
861 | ValueList(Context, Stream.SizeInBytes()) { | ||||
862 | this->ProducerIdentification = std::string(ProducerIdentification); | ||||
863 | } | ||||
864 | |||||
865 | Error BitcodeReader::materializeForwardReferencedFunctions() { | ||||
866 | if (WillMaterializeAllForwardRefs) | ||||
867 | return Error::success(); | ||||
868 | |||||
869 | // Prevent recursion. | ||||
870 | WillMaterializeAllForwardRefs = true; | ||||
871 | |||||
872 | while (!BasicBlockFwdRefQueue.empty()) { | ||||
873 | Function *F = BasicBlockFwdRefQueue.front(); | ||||
874 | BasicBlockFwdRefQueue.pop_front(); | ||||
875 | assert(F && "Expected valid function")((F && "Expected valid function") ? static_cast<void > (0) : __assert_fail ("F && \"Expected valid function\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 875, __PRETTY_FUNCTION__)); | ||||
876 | if (!BasicBlockFwdRefs.count(F)) | ||||
877 | // Already materialized. | ||||
878 | continue; | ||||
879 | |||||
880 | // Check for a function that isn't materializable to prevent an infinite | ||||
881 | // loop. When parsing a blockaddress stored in a global variable, there | ||||
882 | // isn't a trivial way to check if a function will have a body without a | ||||
883 | // linear search through FunctionsWithBodies, so just check it here. | ||||
884 | if (!F->isMaterializable()) | ||||
885 | return error("Never resolved function from blockaddress"); | ||||
886 | |||||
887 | // Try to materialize F. | ||||
888 | if (Error Err = materialize(F)) | ||||
889 | return Err; | ||||
890 | } | ||||
891 | assert(BasicBlockFwdRefs.empty() && "Function missing from queue")((BasicBlockFwdRefs.empty() && "Function missing from queue" ) ? static_cast<void> (0) : __assert_fail ("BasicBlockFwdRefs.empty() && \"Function missing from queue\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 891, __PRETTY_FUNCTION__)); | ||||
892 | |||||
893 | // Reset state. | ||||
894 | WillMaterializeAllForwardRefs = false; | ||||
895 | return Error::success(); | ||||
896 | } | ||||
897 | |||||
898 | //===----------------------------------------------------------------------===// | ||||
899 | // Helper functions to implement forward reference resolution, etc. | ||||
900 | //===----------------------------------------------------------------------===// | ||||
901 | |||||
902 | static bool hasImplicitComdat(size_t Val) { | ||||
903 | switch (Val) { | ||||
904 | default: | ||||
905 | return false; | ||||
906 | case 1: // Old WeakAnyLinkage | ||||
907 | case 4: // Old LinkOnceAnyLinkage | ||||
908 | case 10: // Old WeakODRLinkage | ||||
909 | case 11: // Old LinkOnceODRLinkage | ||||
910 | return true; | ||||
911 | } | ||||
912 | } | ||||
913 | |||||
914 | static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { | ||||
915 | switch (Val) { | ||||
916 | default: // Map unknown/new linkages to external | ||||
917 | case 0: | ||||
918 | return GlobalValue::ExternalLinkage; | ||||
919 | case 2: | ||||
920 | return GlobalValue::AppendingLinkage; | ||||
921 | case 3: | ||||
922 | return GlobalValue::InternalLinkage; | ||||
923 | case 5: | ||||
924 | return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage | ||||
925 | case 6: | ||||
926 | return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage | ||||
927 | case 7: | ||||
928 | return GlobalValue::ExternalWeakLinkage; | ||||
929 | case 8: | ||||
930 | return GlobalValue::CommonLinkage; | ||||
931 | case 9: | ||||
932 | return GlobalValue::PrivateLinkage; | ||||
933 | case 12: | ||||
934 | return GlobalValue::AvailableExternallyLinkage; | ||||
935 | case 13: | ||||
936 | return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage | ||||
937 | case 14: | ||||
938 | return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage | ||||
939 | case 15: | ||||
940 | return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage | ||||
941 | case 1: // Old value with implicit comdat. | ||||
942 | case 16: | ||||
943 | return GlobalValue::WeakAnyLinkage; | ||||
944 | case 10: // Old value with implicit comdat. | ||||
945 | case 17: | ||||
946 | return GlobalValue::WeakODRLinkage; | ||||
947 | case 4: // Old value with implicit comdat. | ||||
948 | case 18: | ||||
949 | return GlobalValue::LinkOnceAnyLinkage; | ||||
950 | case 11: // Old value with implicit comdat. | ||||
951 | case 19: | ||||
952 | return GlobalValue::LinkOnceODRLinkage; | ||||
953 | } | ||||
954 | } | ||||
955 | |||||
956 | static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) { | ||||
957 | FunctionSummary::FFlags Flags; | ||||
958 | Flags.ReadNone = RawFlags & 0x1; | ||||
959 | Flags.ReadOnly = (RawFlags >> 1) & 0x1; | ||||
960 | Flags.NoRecurse = (RawFlags >> 2) & 0x1; | ||||
961 | Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1; | ||||
962 | Flags.NoInline = (RawFlags >> 4) & 0x1; | ||||
963 | Flags.AlwaysInline = (RawFlags >> 5) & 0x1; | ||||
964 | return Flags; | ||||
965 | } | ||||
966 | |||||
967 | /// Decode the flags for GlobalValue in the summary. | ||||
968 | static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, | ||||
969 | uint64_t Version) { | ||||
970 | // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage | ||||
971 | // like getDecodedLinkage() above. Any future change to the linkage enum and | ||||
972 | // to getDecodedLinkage() will need to be taken into account here as above. | ||||
973 | auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits | ||||
974 | RawFlags = RawFlags >> 4; | ||||
975 | bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3; | ||||
976 | // The Live flag wasn't introduced until version 3. For dead stripping | ||||
977 | // to work correctly on earlier versions, we must conservatively treat all | ||||
978 | // values as live. | ||||
979 | bool Live = (RawFlags & 0x2) || Version < 3; | ||||
980 | bool Local = (RawFlags & 0x4); | ||||
981 | bool AutoHide = (RawFlags & 0x8); | ||||
982 | |||||
983 | return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local, AutoHide); | ||||
984 | } | ||||
985 | |||||
986 | // Decode the flags for GlobalVariable in the summary | ||||
987 | static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) { | ||||
988 | return GlobalVarSummary::GVarFlags( | ||||
989 | (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false, | ||||
990 | (RawFlags & 0x4) ? true : false, | ||||
991 | (GlobalObject::VCallVisibility)(RawFlags >> 3)); | ||||
992 | } | ||||
993 | |||||
994 | static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { | ||||
995 | switch (Val) { | ||||
996 | default: // Map unknown visibilities to default. | ||||
997 | case 0: return GlobalValue::DefaultVisibility; | ||||
998 | case 1: return GlobalValue::HiddenVisibility; | ||||
999 | case 2: return GlobalValue::ProtectedVisibility; | ||||
1000 | } | ||||
1001 | } | ||||
1002 | |||||
1003 | static GlobalValue::DLLStorageClassTypes | ||||
1004 | getDecodedDLLStorageClass(unsigned Val) { | ||||
1005 | switch (Val) { | ||||
1006 | default: // Map unknown values to default. | ||||
1007 | case 0: return GlobalValue::DefaultStorageClass; | ||||
1008 | case 1: return GlobalValue::DLLImportStorageClass; | ||||
1009 | case 2: return GlobalValue::DLLExportStorageClass; | ||||
1010 | } | ||||
1011 | } | ||||
1012 | |||||
1013 | static bool getDecodedDSOLocal(unsigned Val) { | ||||
1014 | switch(Val) { | ||||
1015 | default: // Map unknown values to preemptable. | ||||
1016 | case 0: return false; | ||||
1017 | case 1: return true; | ||||
1018 | } | ||||
1019 | } | ||||
1020 | |||||
1021 | static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { | ||||
1022 | switch (Val) { | ||||
1023 | case 0: return GlobalVariable::NotThreadLocal; | ||||
1024 | default: // Map unknown non-zero value to general dynamic. | ||||
1025 | case 1: return GlobalVariable::GeneralDynamicTLSModel; | ||||
1026 | case 2: return GlobalVariable::LocalDynamicTLSModel; | ||||
1027 | case 3: return GlobalVariable::InitialExecTLSModel; | ||||
1028 | case 4: return GlobalVariable::LocalExecTLSModel; | ||||
1029 | } | ||||
1030 | } | ||||
1031 | |||||
1032 | static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { | ||||
1033 | switch (Val) { | ||||
1034 | default: // Map unknown to UnnamedAddr::None. | ||||
1035 | case 0: return GlobalVariable::UnnamedAddr::None; | ||||
1036 | case 1: return GlobalVariable::UnnamedAddr::Global; | ||||
1037 | case 2: return GlobalVariable::UnnamedAddr::Local; | ||||
1038 | } | ||||
1039 | } | ||||
1040 | |||||
1041 | static int getDecodedCastOpcode(unsigned Val) { | ||||
1042 | switch (Val) { | ||||
1043 | default: return -1; | ||||
1044 | case bitc::CAST_TRUNC : return Instruction::Trunc; | ||||
1045 | case bitc::CAST_ZEXT : return Instruction::ZExt; | ||||
1046 | case bitc::CAST_SEXT : return Instruction::SExt; | ||||
1047 | case bitc::CAST_FPTOUI : return Instruction::FPToUI; | ||||
1048 | case bitc::CAST_FPTOSI : return Instruction::FPToSI; | ||||
1049 | case bitc::CAST_UITOFP : return Instruction::UIToFP; | ||||
1050 | case bitc::CAST_SITOFP : return Instruction::SIToFP; | ||||
1051 | case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; | ||||
1052 | case bitc::CAST_FPEXT : return Instruction::FPExt; | ||||
1053 | case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; | ||||
1054 | case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; | ||||
1055 | case bitc::CAST_BITCAST : return Instruction::BitCast; | ||||
1056 | case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; | ||||
1057 | } | ||||
1058 | } | ||||
1059 | |||||
1060 | static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) { | ||||
1061 | bool IsFP = Ty->isFPOrFPVectorTy(); | ||||
1062 | // UnOps are only valid for int/fp or vector of int/fp types | ||||
1063 | if (!IsFP && !Ty->isIntOrIntVectorTy()) | ||||
1064 | return -1; | ||||
1065 | |||||
1066 | switch (Val) { | ||||
1067 | default: | ||||
1068 | return -1; | ||||
1069 | case bitc::UNOP_FNEG: | ||||
1070 | return IsFP ? Instruction::FNeg : -1; | ||||
1071 | } | ||||
1072 | } | ||||
1073 | |||||
1074 | static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { | ||||
1075 | bool IsFP = Ty->isFPOrFPVectorTy(); | ||||
1076 | // BinOps are only valid for int/fp or vector of int/fp types | ||||
1077 | if (!IsFP && !Ty->isIntOrIntVectorTy()) | ||||
1078 | return -1; | ||||
1079 | |||||
1080 | switch (Val) { | ||||
1081 | default: | ||||
1082 | return -1; | ||||
1083 | case bitc::BINOP_ADD: | ||||
1084 | return IsFP ? Instruction::FAdd : Instruction::Add; | ||||
1085 | case bitc::BINOP_SUB: | ||||
1086 | return IsFP ? Instruction::FSub : Instruction::Sub; | ||||
1087 | case bitc::BINOP_MUL: | ||||
1088 | return IsFP ? Instruction::FMul : Instruction::Mul; | ||||
1089 | case bitc::BINOP_UDIV: | ||||
1090 | return IsFP ? -1 : Instruction::UDiv; | ||||
1091 | case bitc::BINOP_SDIV: | ||||
1092 | return IsFP ? Instruction::FDiv : Instruction::SDiv; | ||||
1093 | case bitc::BINOP_UREM: | ||||
1094 | return IsFP ? -1 : Instruction::URem; | ||||
1095 | case bitc::BINOP_SREM: | ||||
1096 | return IsFP ? Instruction::FRem : Instruction::SRem; | ||||
1097 | case bitc::BINOP_SHL: | ||||
1098 | return IsFP ? -1 : Instruction::Shl; | ||||
1099 | case bitc::BINOP_LSHR: | ||||
1100 | return IsFP ? -1 : Instruction::LShr; | ||||
1101 | case bitc::BINOP_ASHR: | ||||
1102 | return IsFP ? -1 : Instruction::AShr; | ||||
1103 | case bitc::BINOP_AND: | ||||
1104 | return IsFP ? -1 : Instruction::And; | ||||
1105 | case bitc::BINOP_OR: | ||||
1106 | return IsFP ? -1 : Instruction::Or; | ||||
1107 | case bitc::BINOP_XOR: | ||||
1108 | return IsFP ? -1 : Instruction::Xor; | ||||
1109 | } | ||||
1110 | } | ||||
1111 | |||||
1112 | static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { | ||||
1113 | switch (Val) { | ||||
1114 | default: return AtomicRMWInst::BAD_BINOP; | ||||
1115 | case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; | ||||
1116 | case bitc::RMW_ADD: return AtomicRMWInst::Add; | ||||
1117 | case bitc::RMW_SUB: return AtomicRMWInst::Sub; | ||||
1118 | case bitc::RMW_AND: return AtomicRMWInst::And; | ||||
1119 | case bitc::RMW_NAND: return AtomicRMWInst::Nand; | ||||
1120 | case bitc::RMW_OR: return AtomicRMWInst::Or; | ||||
1121 | case bitc::RMW_XOR: return AtomicRMWInst::Xor; | ||||
1122 | case bitc::RMW_MAX: return AtomicRMWInst::Max; | ||||
1123 | case bitc::RMW_MIN: return AtomicRMWInst::Min; | ||||
1124 | case bitc::RMW_UMAX: return AtomicRMWInst::UMax; | ||||
1125 | case bitc::RMW_UMIN: return AtomicRMWInst::UMin; | ||||
1126 | case bitc::RMW_FADD: return AtomicRMWInst::FAdd; | ||||
1127 | case bitc::RMW_FSUB: return AtomicRMWInst::FSub; | ||||
1128 | } | ||||
1129 | } | ||||
1130 | |||||
1131 | static AtomicOrdering getDecodedOrdering(unsigned Val) { | ||||
1132 | switch (Val) { | ||||
1133 | case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; | ||||
1134 | case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; | ||||
1135 | case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; | ||||
1136 | case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; | ||||
1137 | case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; | ||||
1138 | case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; | ||||
1139 | default: // Map unknown orderings to sequentially-consistent. | ||||
1140 | case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; | ||||
1141 | } | ||||
1142 | } | ||||
1143 | |||||
1144 | static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { | ||||
1145 | switch (Val) { | ||||
1146 | default: // Map unknown selection kinds to any. | ||||
1147 | case bitc::COMDAT_SELECTION_KIND_ANY: | ||||
1148 | return Comdat::Any; | ||||
1149 | case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: | ||||
1150 | return Comdat::ExactMatch; | ||||
1151 | case bitc::COMDAT_SELECTION_KIND_LARGEST: | ||||
1152 | return Comdat::Largest; | ||||
1153 | case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: | ||||
1154 | return Comdat::NoDuplicates; | ||||
1155 | case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: | ||||
1156 | return Comdat::SameSize; | ||||
1157 | } | ||||
1158 | } | ||||
1159 | |||||
1160 | static FastMathFlags getDecodedFastMathFlags(unsigned Val) { | ||||
1161 | FastMathFlags FMF; | ||||
1162 | if (0 != (Val & bitc::UnsafeAlgebra)) | ||||
1163 | FMF.setFast(); | ||||
1164 | if (0 != (Val & bitc::AllowReassoc)) | ||||
1165 | FMF.setAllowReassoc(); | ||||
1166 | if (0 != (Val & bitc::NoNaNs)) | ||||
1167 | FMF.setNoNaNs(); | ||||
1168 | if (0 != (Val & bitc::NoInfs)) | ||||
1169 | FMF.setNoInfs(); | ||||
1170 | if (0 != (Val & bitc::NoSignedZeros)) | ||||
1171 | FMF.setNoSignedZeros(); | ||||
1172 | if (0 != (Val & bitc::AllowReciprocal)) | ||||
1173 | FMF.setAllowReciprocal(); | ||||
1174 | if (0 != (Val & bitc::AllowContract)) | ||||
1175 | FMF.setAllowContract(true); | ||||
1176 | if (0 != (Val & bitc::ApproxFunc)) | ||||
1177 | FMF.setApproxFunc(); | ||||
1178 | return FMF; | ||||
1179 | } | ||||
1180 | |||||
1181 | static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { | ||||
1182 | switch (Val) { | ||||
1183 | case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; | ||||
1184 | case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; | ||||
1185 | } | ||||
1186 | } | ||||
1187 | |||||
1188 | Type *BitcodeReader::getFullyStructuredTypeByID(unsigned ID) { | ||||
1189 | // The type table size is always specified correctly. | ||||
1190 | if (ID >= TypeList.size()) | ||||
1191 | return nullptr; | ||||
1192 | |||||
1193 | if (Type *Ty = TypeList[ID]) | ||||
1194 | return Ty; | ||||
1195 | |||||
1196 | // If we have a forward reference, the only possible case is when it is to a | ||||
1197 | // named struct. Just create a placeholder for now. | ||||
1198 | return TypeList[ID] = createIdentifiedStructType(Context); | ||||
1199 | } | ||||
1200 | |||||
1201 | StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, | ||||
1202 | StringRef Name) { | ||||
1203 | auto *Ret = StructType::create(Context, Name); | ||||
1204 | IdentifiedStructTypes.push_back(Ret); | ||||
1205 | return Ret; | ||||
1206 | } | ||||
1207 | |||||
1208 | StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { | ||||
1209 | auto *Ret = StructType::create(Context); | ||||
1210 | IdentifiedStructTypes.push_back(Ret); | ||||
1211 | return Ret; | ||||
1212 | } | ||||
1213 | |||||
1214 | //===----------------------------------------------------------------------===// | ||||
1215 | // Functions for parsing blocks from the bitcode file | ||||
1216 | //===----------------------------------------------------------------------===// | ||||
1217 | |||||
1218 | static uint64_t getRawAttributeMask(Attribute::AttrKind Val) { | ||||
1219 | switch (Val) { | ||||
1220 | case Attribute::EndAttrKinds: | ||||
1221 | case Attribute::EmptyKey: | ||||
1222 | case Attribute::TombstoneKey: | ||||
1223 | llvm_unreachable("Synthetic enumerators which should never get here")::llvm::llvm_unreachable_internal("Synthetic enumerators which should never get here" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1223); | ||||
1224 | |||||
1225 | case Attribute::None: return 0; | ||||
1226 | case Attribute::ZExt: return 1 << 0; | ||||
1227 | case Attribute::SExt: return 1 << 1; | ||||
1228 | case Attribute::NoReturn: return 1 << 2; | ||||
1229 | case Attribute::InReg: return 1 << 3; | ||||
1230 | case Attribute::StructRet: return 1 << 4; | ||||
1231 | case Attribute::NoUnwind: return 1 << 5; | ||||
1232 | case Attribute::NoAlias: return 1 << 6; | ||||
1233 | case Attribute::ByVal: return 1 << 7; | ||||
1234 | case Attribute::Nest: return 1 << 8; | ||||
1235 | case Attribute::ReadNone: return 1 << 9; | ||||
1236 | case Attribute::ReadOnly: return 1 << 10; | ||||
1237 | case Attribute::NoInline: return 1 << 11; | ||||
1238 | case Attribute::AlwaysInline: return 1 << 12; | ||||
1239 | case Attribute::OptimizeForSize: return 1 << 13; | ||||
1240 | case Attribute::StackProtect: return 1 << 14; | ||||
1241 | case Attribute::StackProtectReq: return 1 << 15; | ||||
1242 | case Attribute::Alignment: return 31 << 16; | ||||
1243 | case Attribute::NoCapture: return 1 << 21; | ||||
1244 | case Attribute::NoRedZone: return 1 << 22; | ||||
1245 | case Attribute::NoImplicitFloat: return 1 << 23; | ||||
1246 | case Attribute::Naked: return 1 << 24; | ||||
1247 | case Attribute::InlineHint: return 1 << 25; | ||||
1248 | case Attribute::StackAlignment: return 7 << 26; | ||||
1249 | case Attribute::ReturnsTwice: return 1 << 29; | ||||
1250 | case Attribute::UWTable: return 1 << 30; | ||||
1251 | case Attribute::NonLazyBind: return 1U << 31; | ||||
1252 | case Attribute::SanitizeAddress: return 1ULL << 32; | ||||
1253 | case Attribute::MinSize: return 1ULL << 33; | ||||
1254 | case Attribute::NoDuplicate: return 1ULL << 34; | ||||
1255 | case Attribute::StackProtectStrong: return 1ULL << 35; | ||||
1256 | case Attribute::SanitizeThread: return 1ULL << 36; | ||||
1257 | case Attribute::SanitizeMemory: return 1ULL << 37; | ||||
1258 | case Attribute::NoBuiltin: return 1ULL << 38; | ||||
1259 | case Attribute::Returned: return 1ULL << 39; | ||||
1260 | case Attribute::Cold: return 1ULL << 40; | ||||
1261 | case Attribute::Builtin: return 1ULL << 41; | ||||
1262 | case Attribute::OptimizeNone: return 1ULL << 42; | ||||
1263 | case Attribute::InAlloca: return 1ULL << 43; | ||||
1264 | case Attribute::NonNull: return 1ULL << 44; | ||||
1265 | case Attribute::JumpTable: return 1ULL << 45; | ||||
1266 | case Attribute::Convergent: return 1ULL << 46; | ||||
1267 | case Attribute::SafeStack: return 1ULL << 47; | ||||
1268 | case Attribute::NoRecurse: return 1ULL << 48; | ||||
1269 | case Attribute::InaccessibleMemOnly: return 1ULL << 49; | ||||
1270 | case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50; | ||||
1271 | case Attribute::SwiftSelf: return 1ULL << 51; | ||||
1272 | case Attribute::SwiftError: return 1ULL << 52; | ||||
1273 | case Attribute::WriteOnly: return 1ULL << 53; | ||||
1274 | case Attribute::Speculatable: return 1ULL << 54; | ||||
1275 | case Attribute::StrictFP: return 1ULL << 55; | ||||
1276 | case Attribute::SanitizeHWAddress: return 1ULL << 56; | ||||
1277 | case Attribute::NoCfCheck: return 1ULL << 57; | ||||
1278 | case Attribute::OptForFuzzing: return 1ULL << 58; | ||||
1279 | case Attribute::ShadowCallStack: return 1ULL << 59; | ||||
1280 | case Attribute::SpeculativeLoadHardening: | ||||
1281 | return 1ULL << 60; | ||||
1282 | case Attribute::ImmArg: | ||||
1283 | return 1ULL << 61; | ||||
1284 | case Attribute::WillReturn: | ||||
1285 | return 1ULL << 62; | ||||
1286 | case Attribute::NoFree: | ||||
1287 | return 1ULL << 63; | ||||
1288 | case Attribute::NoSync: | ||||
1289 | llvm_unreachable("nosync attribute not supported in raw format")::llvm::llvm_unreachable_internal("nosync attribute not supported in raw format" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1289); | ||||
1290 | break; | ||||
1291 | case Attribute::Dereferenceable: | ||||
1292 | llvm_unreachable("dereferenceable attribute not supported in raw format")::llvm::llvm_unreachable_internal("dereferenceable attribute not supported in raw format" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1292); | ||||
1293 | break; | ||||
1294 | case Attribute::DereferenceableOrNull: | ||||
1295 | llvm_unreachable("dereferenceable_or_null attribute not supported in raw "::llvm::llvm_unreachable_internal("dereferenceable_or_null attribute not supported in raw " "format", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1296) | ||||
1296 | "format")::llvm::llvm_unreachable_internal("dereferenceable_or_null attribute not supported in raw " "format", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1296); | ||||
1297 | break; | ||||
1298 | case Attribute::ArgMemOnly: | ||||
1299 | llvm_unreachable("argmemonly attribute not supported in raw format")::llvm::llvm_unreachable_internal("argmemonly attribute not supported in raw format" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1299); | ||||
1300 | break; | ||||
1301 | case Attribute::AllocSize: | ||||
1302 | llvm_unreachable("allocsize not supported in raw format")::llvm::llvm_unreachable_internal("allocsize not supported in raw format" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1302); | ||||
1303 | break; | ||||
1304 | case Attribute::SanitizeMemTag: | ||||
1305 | llvm_unreachable("sanitize_memtag attribute not supported in raw format")::llvm::llvm_unreachable_internal("sanitize_memtag attribute not supported in raw format" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1305); | ||||
1306 | break; | ||||
1307 | } | ||||
1308 | llvm_unreachable("Unsupported attribute type")::llvm::llvm_unreachable_internal("Unsupported attribute type" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1308); | ||||
1309 | } | ||||
1310 | |||||
1311 | static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { | ||||
1312 | if (!Val) return; | ||||
1313 | |||||
1314 | for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; | ||||
1315 | I = Attribute::AttrKind(I + 1)) { | ||||
1316 | if (I == Attribute::SanitizeMemTag || | ||||
1317 | I == Attribute::Dereferenceable || | ||||
1318 | I == Attribute::DereferenceableOrNull || | ||||
1319 | I == Attribute::ArgMemOnly || | ||||
1320 | I == Attribute::AllocSize || | ||||
1321 | I == Attribute::NoSync) | ||||
1322 | continue; | ||||
1323 | if (uint64_t A = (Val & getRawAttributeMask(I))) { | ||||
1324 | if (I == Attribute::Alignment) | ||||
1325 | B.addAlignmentAttr(1ULL << ((A >> 16) - 1)); | ||||
1326 | else if (I == Attribute::StackAlignment) | ||||
1327 | B.addStackAlignmentAttr(1ULL << ((A >> 26)-1)); | ||||
1328 | else | ||||
1329 | B.addAttribute(I); | ||||
1330 | } | ||||
1331 | } | ||||
1332 | } | ||||
1333 | |||||
1334 | /// This fills an AttrBuilder object with the LLVM attributes that have | ||||
1335 | /// been decoded from the given integer. This function must stay in sync with | ||||
1336 | /// 'encodeLLVMAttributesForBitcode'. | ||||
1337 | static void decodeLLVMAttributesForBitcode(AttrBuilder &B, | ||||
1338 | uint64_t EncodedAttrs) { | ||||
1339 | // FIXME: Remove in 4.0. | ||||
1340 | |||||
1341 | // The alignment is stored as a 16-bit raw value from bits 31--16. We shift | ||||
1342 | // the bits above 31 down by 11 bits. | ||||
1343 | unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; | ||||
1344 | assert((!Alignment || isPowerOf2_32(Alignment)) &&(((!Alignment || isPowerOf2_32(Alignment)) && "Alignment must be a power of two." ) ? static_cast<void> (0) : __assert_fail ("(!Alignment || isPowerOf2_32(Alignment)) && \"Alignment must be a power of two.\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1345, __PRETTY_FUNCTION__)) | ||||
1345 | "Alignment must be a power of two.")(((!Alignment || isPowerOf2_32(Alignment)) && "Alignment must be a power of two." ) ? static_cast<void> (0) : __assert_fail ("(!Alignment || isPowerOf2_32(Alignment)) && \"Alignment must be a power of two.\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1345, __PRETTY_FUNCTION__)); | ||||
1346 | |||||
1347 | if (Alignment) | ||||
1348 | B.addAlignmentAttr(Alignment); | ||||
1349 | addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | | ||||
1350 | (EncodedAttrs & 0xffff)); | ||||
1351 | } | ||||
1352 | |||||
1353 | Error BitcodeReader::parseAttributeBlock() { | ||||
1354 | if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) | ||||
1355 | return Err; | ||||
1356 | |||||
1357 | if (!MAttributes.empty()) | ||||
1358 | return error("Invalid multiple blocks"); | ||||
1359 | |||||
1360 | SmallVector<uint64_t, 64> Record; | ||||
1361 | |||||
1362 | SmallVector<AttributeList, 8> Attrs; | ||||
1363 | |||||
1364 | // Read all the records. | ||||
1365 | while (true) { | ||||
1366 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
1367 | if (!MaybeEntry) | ||||
1368 | return MaybeEntry.takeError(); | ||||
1369 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
1370 | |||||
1371 | switch (Entry.Kind) { | ||||
1372 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
1373 | case BitstreamEntry::Error: | ||||
1374 | return error("Malformed block"); | ||||
1375 | case BitstreamEntry::EndBlock: | ||||
1376 | return Error::success(); | ||||
1377 | case BitstreamEntry::Record: | ||||
1378 | // The interesting case. | ||||
1379 | break; | ||||
1380 | } | ||||
1381 | |||||
1382 | // Read a record. | ||||
1383 | Record.clear(); | ||||
1384 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
1385 | if (!MaybeRecord) | ||||
1386 | return MaybeRecord.takeError(); | ||||
1387 | switch (MaybeRecord.get()) { | ||||
1388 | default: // Default behavior: ignore. | ||||
1389 | break; | ||||
1390 | case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...] | ||||
1391 | // FIXME: Remove in 4.0. | ||||
1392 | if (Record.size() & 1) | ||||
1393 | return error("Invalid record"); | ||||
1394 | |||||
1395 | for (unsigned i = 0, e = Record.size(); i != e; i += 2) { | ||||
1396 | AttrBuilder B; | ||||
1397 | decodeLLVMAttributesForBitcode(B, Record[i+1]); | ||||
1398 | Attrs.push_back(AttributeList::get(Context, Record[i], B)); | ||||
1399 | } | ||||
1400 | |||||
1401 | MAttributes.push_back(AttributeList::get(Context, Attrs)); | ||||
1402 | Attrs.clear(); | ||||
1403 | break; | ||||
1404 | case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...] | ||||
1405 | for (unsigned i = 0, e = Record.size(); i != e; ++i) | ||||
1406 | Attrs.push_back(MAttributeGroups[Record[i]]); | ||||
1407 | |||||
1408 | MAttributes.push_back(AttributeList::get(Context, Attrs)); | ||||
1409 | Attrs.clear(); | ||||
1410 | break; | ||||
1411 | } | ||||
1412 | } | ||||
1413 | } | ||||
1414 | |||||
1415 | // Returns Attribute::None on unrecognized codes. | ||||
1416 | static Attribute::AttrKind getAttrFromCode(uint64_t Code) { | ||||
1417 | switch (Code) { | ||||
1418 | default: | ||||
1419 | return Attribute::None; | ||||
1420 | case bitc::ATTR_KIND_ALIGNMENT: | ||||
1421 | return Attribute::Alignment; | ||||
1422 | case bitc::ATTR_KIND_ALWAYS_INLINE: | ||||
1423 | return Attribute::AlwaysInline; | ||||
1424 | case bitc::ATTR_KIND_ARGMEMONLY: | ||||
1425 | return Attribute::ArgMemOnly; | ||||
1426 | case bitc::ATTR_KIND_BUILTIN: | ||||
1427 | return Attribute::Builtin; | ||||
1428 | case bitc::ATTR_KIND_BY_VAL: | ||||
1429 | return Attribute::ByVal; | ||||
1430 | case bitc::ATTR_KIND_IN_ALLOCA: | ||||
1431 | return Attribute::InAlloca; | ||||
1432 | case bitc::ATTR_KIND_COLD: | ||||
1433 | return Attribute::Cold; | ||||
1434 | case bitc::ATTR_KIND_CONVERGENT: | ||||
1435 | return Attribute::Convergent; | ||||
1436 | case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: | ||||
1437 | return Attribute::InaccessibleMemOnly; | ||||
1438 | case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: | ||||
1439 | return Attribute::InaccessibleMemOrArgMemOnly; | ||||
1440 | case bitc::ATTR_KIND_INLINE_HINT: | ||||
1441 | return Attribute::InlineHint; | ||||
1442 | case bitc::ATTR_KIND_IN_REG: | ||||
1443 | return Attribute::InReg; | ||||
1444 | case bitc::ATTR_KIND_JUMP_TABLE: | ||||
1445 | return Attribute::JumpTable; | ||||
1446 | case bitc::ATTR_KIND_MIN_SIZE: | ||||
1447 | return Attribute::MinSize; | ||||
1448 | case bitc::ATTR_KIND_NAKED: | ||||
1449 | return Attribute::Naked; | ||||
1450 | case bitc::ATTR_KIND_NEST: | ||||
1451 | return Attribute::Nest; | ||||
1452 | case bitc::ATTR_KIND_NO_ALIAS: | ||||
1453 | return Attribute::NoAlias; | ||||
1454 | case bitc::ATTR_KIND_NO_BUILTIN: | ||||
1455 | return Attribute::NoBuiltin; | ||||
1456 | case bitc::ATTR_KIND_NO_CAPTURE: | ||||
1457 | return Attribute::NoCapture; | ||||
1458 | case bitc::ATTR_KIND_NO_DUPLICATE: | ||||
1459 | return Attribute::NoDuplicate; | ||||
1460 | case bitc::ATTR_KIND_NOFREE: | ||||
1461 | return Attribute::NoFree; | ||||
1462 | case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: | ||||
1463 | return Attribute::NoImplicitFloat; | ||||
1464 | case bitc::ATTR_KIND_NO_INLINE: | ||||
1465 | return Attribute::NoInline; | ||||
1466 | case bitc::ATTR_KIND_NO_RECURSE: | ||||
1467 | return Attribute::NoRecurse; | ||||
1468 | case bitc::ATTR_KIND_NON_LAZY_BIND: | ||||
1469 | return Attribute::NonLazyBind; | ||||
1470 | case bitc::ATTR_KIND_NON_NULL: | ||||
1471 | return Attribute::NonNull; | ||||
1472 | case bitc::ATTR_KIND_DEREFERENCEABLE: | ||||
1473 | return Attribute::Dereferenceable; | ||||
1474 | case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: | ||||
1475 | return Attribute::DereferenceableOrNull; | ||||
1476 | case bitc::ATTR_KIND_ALLOC_SIZE: | ||||
1477 | return Attribute::AllocSize; | ||||
1478 | case bitc::ATTR_KIND_NO_RED_ZONE: | ||||
1479 | return Attribute::NoRedZone; | ||||
1480 | case bitc::ATTR_KIND_NO_RETURN: | ||||
1481 | return Attribute::NoReturn; | ||||
1482 | case bitc::ATTR_KIND_NOSYNC: | ||||
1483 | return Attribute::NoSync; | ||||
1484 | case bitc::ATTR_KIND_NOCF_CHECK: | ||||
1485 | return Attribute::NoCfCheck; | ||||
1486 | case bitc::ATTR_KIND_NO_UNWIND: | ||||
1487 | return Attribute::NoUnwind; | ||||
1488 | case bitc::ATTR_KIND_OPT_FOR_FUZZING: | ||||
1489 | return Attribute::OptForFuzzing; | ||||
1490 | case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: | ||||
1491 | return Attribute::OptimizeForSize; | ||||
1492 | case bitc::ATTR_KIND_OPTIMIZE_NONE: | ||||
1493 | return Attribute::OptimizeNone; | ||||
1494 | case bitc::ATTR_KIND_READ_NONE: | ||||
1495 | return Attribute::ReadNone; | ||||
1496 | case bitc::ATTR_KIND_READ_ONLY: | ||||
1497 | return Attribute::ReadOnly; | ||||
1498 | case bitc::ATTR_KIND_RETURNED: | ||||
1499 | return Attribute::Returned; | ||||
1500 | case bitc::ATTR_KIND_RETURNS_TWICE: | ||||
1501 | return Attribute::ReturnsTwice; | ||||
1502 | case bitc::ATTR_KIND_S_EXT: | ||||
1503 | return Attribute::SExt; | ||||
1504 | case bitc::ATTR_KIND_SPECULATABLE: | ||||
1505 | return Attribute::Speculatable; | ||||
1506 | case bitc::ATTR_KIND_STACK_ALIGNMENT: | ||||
1507 | return Attribute::StackAlignment; | ||||
1508 | case bitc::ATTR_KIND_STACK_PROTECT: | ||||
1509 | return Attribute::StackProtect; | ||||
1510 | case bitc::ATTR_KIND_STACK_PROTECT_REQ: | ||||
1511 | return Attribute::StackProtectReq; | ||||
1512 | case bitc::ATTR_KIND_STACK_PROTECT_STRONG: | ||||
1513 | return Attribute::StackProtectStrong; | ||||
1514 | case bitc::ATTR_KIND_SAFESTACK: | ||||
1515 | return Attribute::SafeStack; | ||||
1516 | case bitc::ATTR_KIND_SHADOWCALLSTACK: | ||||
1517 | return Attribute::ShadowCallStack; | ||||
1518 | case bitc::ATTR_KIND_STRICT_FP: | ||||
1519 | return Attribute::StrictFP; | ||||
1520 | case bitc::ATTR_KIND_STRUCT_RET: | ||||
1521 | return Attribute::StructRet; | ||||
1522 | case bitc::ATTR_KIND_SANITIZE_ADDRESS: | ||||
1523 | return Attribute::SanitizeAddress; | ||||
1524 | case bitc::ATTR_KIND_SANITIZE_HWADDRESS: | ||||
1525 | return Attribute::SanitizeHWAddress; | ||||
1526 | case bitc::ATTR_KIND_SANITIZE_THREAD: | ||||
1527 | return Attribute::SanitizeThread; | ||||
1528 | case bitc::ATTR_KIND_SANITIZE_MEMORY: | ||||
1529 | return Attribute::SanitizeMemory; | ||||
1530 | case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING: | ||||
1531 | return Attribute::SpeculativeLoadHardening; | ||||
1532 | case bitc::ATTR_KIND_SWIFT_ERROR: | ||||
1533 | return Attribute::SwiftError; | ||||
1534 | case bitc::ATTR_KIND_SWIFT_SELF: | ||||
1535 | return Attribute::SwiftSelf; | ||||
1536 | case bitc::ATTR_KIND_UW_TABLE: | ||||
1537 | return Attribute::UWTable; | ||||
1538 | case bitc::ATTR_KIND_WILLRETURN: | ||||
1539 | return Attribute::WillReturn; | ||||
1540 | case bitc::ATTR_KIND_WRITEONLY: | ||||
1541 | return Attribute::WriteOnly; | ||||
1542 | case bitc::ATTR_KIND_Z_EXT: | ||||
1543 | return Attribute::ZExt; | ||||
1544 | case bitc::ATTR_KIND_IMMARG: | ||||
1545 | return Attribute::ImmArg; | ||||
1546 | case bitc::ATTR_KIND_SANITIZE_MEMTAG: | ||||
1547 | return Attribute::SanitizeMemTag; | ||||
1548 | } | ||||
1549 | } | ||||
1550 | |||||
1551 | Error BitcodeReader::parseAlignmentValue(uint64_t Exponent, | ||||
1552 | MaybeAlign &Alignment) { | ||||
1553 | // Note: Alignment in bitcode files is incremented by 1, so that zero | ||||
1554 | // can be used for default alignment. | ||||
1555 | if (Exponent > Value::MaxAlignmentExponent + 1) | ||||
1556 | return error("Invalid alignment value"); | ||||
1557 | Alignment = decodeMaybeAlign(Exponent); | ||||
1558 | return Error::success(); | ||||
1559 | } | ||||
1560 | |||||
1561 | Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) { | ||||
1562 | *Kind = getAttrFromCode(Code); | ||||
1563 | if (*Kind == Attribute::None) | ||||
1564 | return error("Unknown attribute kind (" + Twine(Code) + ")"); | ||||
1565 | return Error::success(); | ||||
1566 | } | ||||
1567 | |||||
1568 | Error BitcodeReader::parseAttributeGroupBlock() { | ||||
1569 | if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) | ||||
1570 | return Err; | ||||
1571 | |||||
1572 | if (!MAttributeGroups.empty()) | ||||
1573 | return error("Invalid multiple blocks"); | ||||
1574 | |||||
1575 | SmallVector<uint64_t, 64> Record; | ||||
1576 | |||||
1577 | // Read all the records. | ||||
1578 | while (true) { | ||||
1579 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
1580 | if (!MaybeEntry) | ||||
1581 | return MaybeEntry.takeError(); | ||||
1582 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
1583 | |||||
1584 | switch (Entry.Kind) { | ||||
1585 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
1586 | case BitstreamEntry::Error: | ||||
1587 | return error("Malformed block"); | ||||
1588 | case BitstreamEntry::EndBlock: | ||||
1589 | return Error::success(); | ||||
1590 | case BitstreamEntry::Record: | ||||
1591 | // The interesting case. | ||||
1592 | break; | ||||
1593 | } | ||||
1594 | |||||
1595 | // Read a record. | ||||
1596 | Record.clear(); | ||||
1597 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
1598 | if (!MaybeRecord) | ||||
1599 | return MaybeRecord.takeError(); | ||||
1600 | switch (MaybeRecord.get()) { | ||||
1601 | default: // Default behavior: ignore. | ||||
1602 | break; | ||||
1603 | case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] | ||||
1604 | if (Record.size() < 3) | ||||
1605 | return error("Invalid record"); | ||||
1606 | |||||
1607 | uint64_t GrpID = Record[0]; | ||||
1608 | uint64_t Idx = Record[1]; // Index of the object this attribute refers to. | ||||
1609 | |||||
1610 | AttrBuilder B; | ||||
1611 | for (unsigned i = 2, e = Record.size(); i != e; ++i) { | ||||
1612 | if (Record[i] == 0) { // Enum attribute | ||||
1613 | Attribute::AttrKind Kind; | ||||
1614 | if (Error Err = parseAttrKind(Record[++i], &Kind)) | ||||
1615 | return Err; | ||||
1616 | |||||
1617 | // Upgrade old-style byval attribute to one with a type, even if it's | ||||
1618 | // nullptr. We will have to insert the real type when we associate | ||||
1619 | // this AttributeList with a function. | ||||
1620 | if (Kind == Attribute::ByVal) | ||||
1621 | B.addByValAttr(nullptr); | ||||
1622 | |||||
1623 | B.addAttribute(Kind); | ||||
1624 | } else if (Record[i] == 1) { // Integer attribute | ||||
1625 | Attribute::AttrKind Kind; | ||||
1626 | if (Error Err = parseAttrKind(Record[++i], &Kind)) | ||||
1627 | return Err; | ||||
1628 | if (Kind == Attribute::Alignment) | ||||
1629 | B.addAlignmentAttr(Record[++i]); | ||||
1630 | else if (Kind == Attribute::StackAlignment) | ||||
1631 | B.addStackAlignmentAttr(Record[++i]); | ||||
1632 | else if (Kind == Attribute::Dereferenceable) | ||||
1633 | B.addDereferenceableAttr(Record[++i]); | ||||
1634 | else if (Kind == Attribute::DereferenceableOrNull) | ||||
1635 | B.addDereferenceableOrNullAttr(Record[++i]); | ||||
1636 | else if (Kind == Attribute::AllocSize) | ||||
1637 | B.addAllocSizeAttrFromRawRepr(Record[++i]); | ||||
1638 | } else if (Record[i] == 3 || Record[i] == 4) { // String attribute | ||||
1639 | bool HasValue = (Record[i++] == 4); | ||||
1640 | SmallString<64> KindStr; | ||||
1641 | SmallString<64> ValStr; | ||||
1642 | |||||
1643 | while (Record[i] != 0 && i != e) | ||||
1644 | KindStr += Record[i++]; | ||||
1645 | assert(Record[i] == 0 && "Kind string not null terminated")((Record[i] == 0 && "Kind string not null terminated" ) ? static_cast<void> (0) : __assert_fail ("Record[i] == 0 && \"Kind string not null terminated\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1645, __PRETTY_FUNCTION__)); | ||||
1646 | |||||
1647 | if (HasValue) { | ||||
1648 | // Has a value associated with it. | ||||
1649 | ++i; // Skip the '0' that terminates the "kind" string. | ||||
1650 | while (Record[i] != 0 && i != e) | ||||
1651 | ValStr += Record[i++]; | ||||
1652 | assert(Record[i] == 0 && "Value string not null terminated")((Record[i] == 0 && "Value string not null terminated" ) ? static_cast<void> (0) : __assert_fail ("Record[i] == 0 && \"Value string not null terminated\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1652, __PRETTY_FUNCTION__)); | ||||
1653 | } | ||||
1654 | |||||
1655 | B.addAttribute(KindStr.str(), ValStr.str()); | ||||
1656 | } else { | ||||
1657 | assert((Record[i] == 5 || Record[i] == 6) &&(((Record[i] == 5 || Record[i] == 6) && "Invalid attribute group entry" ) ? static_cast<void> (0) : __assert_fail ("(Record[i] == 5 || Record[i] == 6) && \"Invalid attribute group entry\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1658, __PRETTY_FUNCTION__)) | ||||
1658 | "Invalid attribute group entry")(((Record[i] == 5 || Record[i] == 6) && "Invalid attribute group entry" ) ? static_cast<void> (0) : __assert_fail ("(Record[i] == 5 || Record[i] == 6) && \"Invalid attribute group entry\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1658, __PRETTY_FUNCTION__)); | ||||
1659 | bool HasType = Record[i] == 6; | ||||
1660 | Attribute::AttrKind Kind; | ||||
1661 | if (Error Err = parseAttrKind(Record[++i], &Kind)) | ||||
1662 | return Err; | ||||
1663 | if (Kind == Attribute::ByVal) | ||||
1664 | B.addByValAttr(HasType ? getTypeByID(Record[++i]) : nullptr); | ||||
1665 | } | ||||
1666 | } | ||||
1667 | |||||
1668 | UpgradeFramePointerAttributes(B); | ||||
1669 | MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B); | ||||
1670 | break; | ||||
1671 | } | ||||
1672 | } | ||||
1673 | } | ||||
1674 | } | ||||
1675 | |||||
1676 | Error BitcodeReader::parseTypeTable() { | ||||
1677 | if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) | ||||
1678 | return Err; | ||||
1679 | |||||
1680 | return parseTypeTableBody(); | ||||
1681 | } | ||||
1682 | |||||
1683 | Error BitcodeReader::parseTypeTableBody() { | ||||
1684 | if (!TypeList.empty()) | ||||
1685 | return error("Invalid multiple blocks"); | ||||
1686 | |||||
1687 | SmallVector<uint64_t, 64> Record; | ||||
1688 | unsigned NumRecords = 0; | ||||
1689 | |||||
1690 | SmallString<64> TypeName; | ||||
1691 | |||||
1692 | // Read all the records for this type table. | ||||
1693 | while (true) { | ||||
1694 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
1695 | if (!MaybeEntry) | ||||
1696 | return MaybeEntry.takeError(); | ||||
1697 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
1698 | |||||
1699 | switch (Entry.Kind) { | ||||
1700 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
1701 | case BitstreamEntry::Error: | ||||
1702 | return error("Malformed block"); | ||||
1703 | case BitstreamEntry::EndBlock: | ||||
1704 | if (NumRecords != TypeList.size()) | ||||
1705 | return error("Malformed block"); | ||||
1706 | return Error::success(); | ||||
1707 | case BitstreamEntry::Record: | ||||
1708 | // The interesting case. | ||||
1709 | break; | ||||
1710 | } | ||||
1711 | |||||
1712 | // Read a record. | ||||
1713 | Record.clear(); | ||||
1714 | Type *ResultTy = nullptr; | ||||
1715 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
1716 | if (!MaybeRecord) | ||||
1717 | return MaybeRecord.takeError(); | ||||
1718 | switch (MaybeRecord.get()) { | ||||
1719 | default: | ||||
1720 | return error("Invalid value"); | ||||
1721 | case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] | ||||
1722 | // TYPE_CODE_NUMENTRY contains a count of the number of types in the | ||||
1723 | // type list. This allows us to reserve space. | ||||
1724 | if (Record.size() < 1) | ||||
1725 | return error("Invalid record"); | ||||
1726 | TypeList.resize(Record[0]); | ||||
1727 | continue; | ||||
1728 | case bitc::TYPE_CODE_VOID: // VOID | ||||
1729 | ResultTy = Type::getVoidTy(Context); | ||||
1730 | break; | ||||
1731 | case bitc::TYPE_CODE_HALF: // HALF | ||||
1732 | ResultTy = Type::getHalfTy(Context); | ||||
1733 | break; | ||||
1734 | case bitc::TYPE_CODE_FLOAT: // FLOAT | ||||
1735 | ResultTy = Type::getFloatTy(Context); | ||||
1736 | break; | ||||
1737 | case bitc::TYPE_CODE_DOUBLE: // DOUBLE | ||||
1738 | ResultTy = Type::getDoubleTy(Context); | ||||
1739 | break; | ||||
1740 | case bitc::TYPE_CODE_X86_FP80: // X86_FP80 | ||||
1741 | ResultTy = Type::getX86_FP80Ty(Context); | ||||
1742 | break; | ||||
1743 | case bitc::TYPE_CODE_FP128: // FP128 | ||||
1744 | ResultTy = Type::getFP128Ty(Context); | ||||
1745 | break; | ||||
1746 | case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 | ||||
1747 | ResultTy = Type::getPPC_FP128Ty(Context); | ||||
1748 | break; | ||||
1749 | case bitc::TYPE_CODE_LABEL: // LABEL | ||||
1750 | ResultTy = Type::getLabelTy(Context); | ||||
1751 | break; | ||||
1752 | case bitc::TYPE_CODE_METADATA: // METADATA | ||||
1753 | ResultTy = Type::getMetadataTy(Context); | ||||
1754 | break; | ||||
1755 | case bitc::TYPE_CODE_X86_MMX: // X86_MMX | ||||
1756 | ResultTy = Type::getX86_MMXTy(Context); | ||||
1757 | break; | ||||
1758 | case bitc::TYPE_CODE_TOKEN: // TOKEN | ||||
1759 | ResultTy = Type::getTokenTy(Context); | ||||
1760 | break; | ||||
1761 | case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] | ||||
1762 | if (Record.size() < 1) | ||||
1763 | return error("Invalid record"); | ||||
1764 | |||||
1765 | uint64_t NumBits = Record[0]; | ||||
1766 | if (NumBits < IntegerType::MIN_INT_BITS || | ||||
1767 | NumBits > IntegerType::MAX_INT_BITS) | ||||
1768 | return error("Bitwidth for integer type out of range"); | ||||
1769 | ResultTy = IntegerType::get(Context, NumBits); | ||||
1770 | break; | ||||
1771 | } | ||||
1772 | case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or | ||||
1773 | // [pointee type, address space] | ||||
1774 | if (Record.size() < 1) | ||||
1775 | return error("Invalid record"); | ||||
1776 | unsigned AddressSpace = 0; | ||||
1777 | if (Record.size() == 2) | ||||
1778 | AddressSpace = Record[1]; | ||||
1779 | ResultTy = getTypeByID(Record[0]); | ||||
1780 | if (!ResultTy || | ||||
1781 | !PointerType::isValidElementType(ResultTy)) | ||||
1782 | return error("Invalid type"); | ||||
1783 | ResultTy = PointerType::get(ResultTy, AddressSpace); | ||||
1784 | break; | ||||
1785 | } | ||||
1786 | case bitc::TYPE_CODE_FUNCTION_OLD: { | ||||
1787 | // FIXME: attrid is dead, remove it in LLVM 4.0 | ||||
1788 | // FUNCTION: [vararg, attrid, retty, paramty x N] | ||||
1789 | if (Record.size() < 3) | ||||
1790 | return error("Invalid record"); | ||||
1791 | SmallVector<Type*, 8> ArgTys; | ||||
1792 | for (unsigned i = 3, e = Record.size(); i != e; ++i) { | ||||
1793 | if (Type *T = getTypeByID(Record[i])) | ||||
1794 | ArgTys.push_back(T); | ||||
1795 | else | ||||
1796 | break; | ||||
1797 | } | ||||
1798 | |||||
1799 | ResultTy = getTypeByID(Record[2]); | ||||
1800 | if (!ResultTy || ArgTys.size() < Record.size()-3) | ||||
1801 | return error("Invalid type"); | ||||
1802 | |||||
1803 | ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); | ||||
1804 | break; | ||||
1805 | } | ||||
1806 | case bitc::TYPE_CODE_FUNCTION: { | ||||
1807 | // FUNCTION: [vararg, retty, paramty x N] | ||||
1808 | if (Record.size() < 2) | ||||
1809 | return error("Invalid record"); | ||||
1810 | SmallVector<Type*, 8> ArgTys; | ||||
1811 | for (unsigned i = 2, e = Record.size(); i != e; ++i) { | ||||
1812 | if (Type *T = getTypeByID(Record[i])) { | ||||
1813 | if (!FunctionType::isValidArgumentType(T)) | ||||
1814 | return error("Invalid function argument type"); | ||||
1815 | ArgTys.push_back(T); | ||||
1816 | } | ||||
1817 | else | ||||
1818 | break; | ||||
1819 | } | ||||
1820 | |||||
1821 | ResultTy = getTypeByID(Record[1]); | ||||
1822 | if (!ResultTy || ArgTys.size() < Record.size()-2) | ||||
1823 | return error("Invalid type"); | ||||
1824 | |||||
1825 | ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); | ||||
1826 | break; | ||||
1827 | } | ||||
1828 | case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] | ||||
1829 | if (Record.size() < 1) | ||||
1830 | return error("Invalid record"); | ||||
1831 | SmallVector<Type*, 8> EltTys; | ||||
1832 | for (unsigned i = 1, e = Record.size(); i != e; ++i) { | ||||
1833 | if (Type *T = getTypeByID(Record[i])) | ||||
1834 | EltTys.push_back(T); | ||||
1835 | else | ||||
1836 | break; | ||||
1837 | } | ||||
1838 | if (EltTys.size() != Record.size()-1) | ||||
1839 | return error("Invalid type"); | ||||
1840 | ResultTy = StructType::get(Context, EltTys, Record[0]); | ||||
1841 | break; | ||||
1842 | } | ||||
1843 | case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] | ||||
1844 | if (convertToString(Record, 0, TypeName)) | ||||
1845 | return error("Invalid record"); | ||||
1846 | continue; | ||||
1847 | |||||
1848 | case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] | ||||
1849 | if (Record.size() < 1) | ||||
1850 | return error("Invalid record"); | ||||
1851 | |||||
1852 | if (NumRecords >= TypeList.size()) | ||||
1853 | return error("Invalid TYPE table"); | ||||
1854 | |||||
1855 | // Check to see if this was forward referenced, if so fill in the temp. | ||||
1856 | StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); | ||||
1857 | if (Res) { | ||||
1858 | Res->setName(TypeName); | ||||
1859 | TypeList[NumRecords] = nullptr; | ||||
1860 | } else // Otherwise, create a new struct. | ||||
1861 | Res = createIdentifiedStructType(Context, TypeName); | ||||
1862 | TypeName.clear(); | ||||
1863 | |||||
1864 | SmallVector<Type*, 8> EltTys; | ||||
1865 | for (unsigned i = 1, e = Record.size(); i != e; ++i) { | ||||
1866 | if (Type *T = getTypeByID(Record[i])) | ||||
1867 | EltTys.push_back(T); | ||||
1868 | else | ||||
1869 | break; | ||||
1870 | } | ||||
1871 | if (EltTys.size() != Record.size()-1) | ||||
1872 | return error("Invalid record"); | ||||
1873 | Res->setBody(EltTys, Record[0]); | ||||
1874 | ResultTy = Res; | ||||
1875 | break; | ||||
1876 | } | ||||
1877 | case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] | ||||
1878 | if (Record.size() != 1) | ||||
1879 | return error("Invalid record"); | ||||
1880 | |||||
1881 | if (NumRecords >= TypeList.size()) | ||||
1882 | return error("Invalid TYPE table"); | ||||
1883 | |||||
1884 | // Check to see if this was forward referenced, if so fill in the temp. | ||||
1885 | StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); | ||||
1886 | if (Res) { | ||||
1887 | Res->setName(TypeName); | ||||
1888 | TypeList[NumRecords] = nullptr; | ||||
1889 | } else // Otherwise, create a new struct with no body. | ||||
1890 | Res = createIdentifiedStructType(Context, TypeName); | ||||
1891 | TypeName.clear(); | ||||
1892 | ResultTy = Res; | ||||
1893 | break; | ||||
1894 | } | ||||
1895 | case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] | ||||
1896 | if (Record.size() < 2) | ||||
1897 | return error("Invalid record"); | ||||
1898 | ResultTy = getTypeByID(Record[1]); | ||||
1899 | if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) | ||||
1900 | return error("Invalid type"); | ||||
1901 | ResultTy = ArrayType::get(ResultTy, Record[0]); | ||||
1902 | break; | ||||
1903 | case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or | ||||
1904 | // [numelts, eltty, scalable] | ||||
1905 | if (Record.size() < 2) | ||||
1906 | return error("Invalid record"); | ||||
1907 | if (Record[0] == 0) | ||||
1908 | return error("Invalid vector length"); | ||||
1909 | ResultTy = getTypeByID(Record[1]); | ||||
1910 | if (!ResultTy || !StructType::isValidElementType(ResultTy)) | ||||
1911 | return error("Invalid type"); | ||||
1912 | bool Scalable = Record.size() > 2 ? Record[2] : false; | ||||
1913 | ResultTy = VectorType::get(ResultTy, Record[0], Scalable); | ||||
1914 | break; | ||||
1915 | } | ||||
1916 | |||||
1917 | if (NumRecords >= TypeList.size()) | ||||
1918 | return error("Invalid TYPE table"); | ||||
1919 | if (TypeList[NumRecords]) | ||||
1920 | return error( | ||||
1921 | "Invalid TYPE table: Only named structs can be forward referenced"); | ||||
1922 | assert(ResultTy && "Didn't read a type?")((ResultTy && "Didn't read a type?") ? static_cast< void> (0) : __assert_fail ("ResultTy && \"Didn't read a type?\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 1922, __PRETTY_FUNCTION__)); | ||||
1923 | TypeList[NumRecords++] = ResultTy; | ||||
1924 | } | ||||
1925 | } | ||||
1926 | |||||
1927 | Error BitcodeReader::parseOperandBundleTags() { | ||||
1928 | if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) | ||||
1929 | return Err; | ||||
1930 | |||||
1931 | if (!BundleTags.empty()) | ||||
1932 | return error("Invalid multiple blocks"); | ||||
1933 | |||||
1934 | SmallVector<uint64_t, 64> Record; | ||||
1935 | |||||
1936 | while (true) { | ||||
1937 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
1938 | if (!MaybeEntry) | ||||
1939 | return MaybeEntry.takeError(); | ||||
1940 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
1941 | |||||
1942 | switch (Entry.Kind) { | ||||
1943 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
1944 | case BitstreamEntry::Error: | ||||
1945 | return error("Malformed block"); | ||||
1946 | case BitstreamEntry::EndBlock: | ||||
1947 | return Error::success(); | ||||
1948 | case BitstreamEntry::Record: | ||||
1949 | // The interesting case. | ||||
1950 | break; | ||||
1951 | } | ||||
1952 | |||||
1953 | // Tags are implicitly mapped to integers by their order. | ||||
1954 | |||||
1955 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
1956 | if (!MaybeRecord) | ||||
1957 | return MaybeRecord.takeError(); | ||||
1958 | if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG) | ||||
1959 | return error("Invalid record"); | ||||
1960 | |||||
1961 | // OPERAND_BUNDLE_TAG: [strchr x N] | ||||
1962 | BundleTags.emplace_back(); | ||||
1963 | if (convertToString(Record, 0, BundleTags.back())) | ||||
1964 | return error("Invalid record"); | ||||
1965 | Record.clear(); | ||||
1966 | } | ||||
1967 | } | ||||
1968 | |||||
1969 | Error BitcodeReader::parseSyncScopeNames() { | ||||
1970 | if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID)) | ||||
1971 | return Err; | ||||
1972 | |||||
1973 | if (!SSIDs.empty()) | ||||
1974 | return error("Invalid multiple synchronization scope names blocks"); | ||||
1975 | |||||
1976 | SmallVector<uint64_t, 64> Record; | ||||
1977 | while (true) { | ||||
1978 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
1979 | if (!MaybeEntry) | ||||
1980 | return MaybeEntry.takeError(); | ||||
1981 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
1982 | |||||
1983 | switch (Entry.Kind) { | ||||
1984 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
1985 | case BitstreamEntry::Error: | ||||
1986 | return error("Malformed block"); | ||||
1987 | case BitstreamEntry::EndBlock: | ||||
1988 | if (SSIDs.empty()) | ||||
1989 | return error("Invalid empty synchronization scope names block"); | ||||
1990 | return Error::success(); | ||||
1991 | case BitstreamEntry::Record: | ||||
1992 | // The interesting case. | ||||
1993 | break; | ||||
1994 | } | ||||
1995 | |||||
1996 | // Synchronization scope names are implicitly mapped to synchronization | ||||
1997 | // scope IDs by their order. | ||||
1998 | |||||
1999 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
2000 | if (!MaybeRecord) | ||||
2001 | return MaybeRecord.takeError(); | ||||
2002 | if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME) | ||||
2003 | return error("Invalid record"); | ||||
2004 | |||||
2005 | SmallString<16> SSN; | ||||
2006 | if (convertToString(Record, 0, SSN)) | ||||
2007 | return error("Invalid record"); | ||||
2008 | |||||
2009 | SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN)); | ||||
2010 | Record.clear(); | ||||
2011 | } | ||||
2012 | } | ||||
2013 | |||||
2014 | /// Associate a value with its name from the given index in the provided record. | ||||
2015 | Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, | ||||
2016 | unsigned NameIndex, Triple &TT) { | ||||
2017 | SmallString<128> ValueName; | ||||
2018 | if (convertToString(Record, NameIndex, ValueName)) | ||||
2019 | return error("Invalid record"); | ||||
2020 | unsigned ValueID = Record[0]; | ||||
2021 | if (ValueID >= ValueList.size() || !ValueList[ValueID]) | ||||
2022 | return error("Invalid record"); | ||||
2023 | Value *V = ValueList[ValueID]; | ||||
2024 | |||||
2025 | StringRef NameStr(ValueName.data(), ValueName.size()); | ||||
2026 | if (NameStr.find_first_of(0) != StringRef::npos) | ||||
2027 | return error("Invalid value name"); | ||||
2028 | V->setName(NameStr); | ||||
2029 | auto *GO = dyn_cast<GlobalObject>(V); | ||||
2030 | if (GO) { | ||||
2031 | if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) { | ||||
2032 | if (TT.supportsCOMDAT()) | ||||
2033 | GO->setComdat(TheModule->getOrInsertComdat(V->getName())); | ||||
2034 | else | ||||
2035 | GO->setComdat(nullptr); | ||||
2036 | } | ||||
2037 | } | ||||
2038 | return V; | ||||
2039 | } | ||||
2040 | |||||
2041 | /// Helper to note and return the current location, and jump to the given | ||||
2042 | /// offset. | ||||
2043 | static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset, | ||||
2044 | BitstreamCursor &Stream) { | ||||
2045 | // Save the current parsing location so we can jump back at the end | ||||
2046 | // of the VST read. | ||||
2047 | uint64_t CurrentBit = Stream.GetCurrentBitNo(); | ||||
2048 | if (Error JumpFailed = Stream.JumpToBit(Offset * 32)) | ||||
2049 | return std::move(JumpFailed); | ||||
2050 | Expected<BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
2051 | if (!MaybeEntry) | ||||
2052 | return MaybeEntry.takeError(); | ||||
2053 | assert(MaybeEntry.get().Kind == BitstreamEntry::SubBlock)((MaybeEntry.get().Kind == BitstreamEntry::SubBlock) ? static_cast <void> (0) : __assert_fail ("MaybeEntry.get().Kind == BitstreamEntry::SubBlock" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 2053, __PRETTY_FUNCTION__)); | ||||
2054 | assert(MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID)((MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID) ? static_cast <void> (0) : __assert_fail ("MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 2054, __PRETTY_FUNCTION__)); | ||||
2055 | return CurrentBit; | ||||
2056 | } | ||||
2057 | |||||
2058 | void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, | ||||
2059 | Function *F, | ||||
2060 | ArrayRef<uint64_t> Record) { | ||||
2061 | // Note that we subtract 1 here because the offset is relative to one word | ||||
2062 | // before the start of the identification or module block, which was | ||||
2063 | // historically always the start of the regular bitcode header. | ||||
2064 | uint64_t FuncWordOffset = Record[1] - 1; | ||||
2065 | uint64_t FuncBitOffset = FuncWordOffset * 32; | ||||
2066 | DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; | ||||
2067 | // Set the LastFunctionBlockBit to point to the last function block. | ||||
2068 | // Later when parsing is resumed after function materialization, | ||||
2069 | // we can simply skip that last function block. | ||||
2070 | if (FuncBitOffset > LastFunctionBlockBit) | ||||
2071 | LastFunctionBlockBit = FuncBitOffset; | ||||
2072 | } | ||||
2073 | |||||
2074 | /// Read a new-style GlobalValue symbol table. | ||||
2075 | Error BitcodeReader::parseGlobalValueSymbolTable() { | ||||
2076 | unsigned FuncBitcodeOffsetDelta = | ||||
2077 | Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; | ||||
2078 | |||||
2079 | if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) | ||||
2080 | return Err; | ||||
2081 | |||||
2082 | SmallVector<uint64_t, 64> Record; | ||||
2083 | while (true) { | ||||
2084 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
2085 | if (!MaybeEntry) | ||||
2086 | return MaybeEntry.takeError(); | ||||
2087 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
2088 | |||||
2089 | switch (Entry.Kind) { | ||||
2090 | case BitstreamEntry::SubBlock: | ||||
2091 | case BitstreamEntry::Error: | ||||
2092 | return error("Malformed block"); | ||||
2093 | case BitstreamEntry::EndBlock: | ||||
2094 | return Error::success(); | ||||
2095 | case BitstreamEntry::Record: | ||||
2096 | break; | ||||
2097 | } | ||||
2098 | |||||
2099 | Record.clear(); | ||||
2100 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
2101 | if (!MaybeRecord) | ||||
2102 | return MaybeRecord.takeError(); | ||||
2103 | switch (MaybeRecord.get()) { | ||||
2104 | case bitc::VST_CODE_FNENTRY: // [valueid, offset] | ||||
2105 | setDeferredFunctionInfo(FuncBitcodeOffsetDelta, | ||||
2106 | cast<Function>(ValueList[Record[0]]), Record); | ||||
2107 | break; | ||||
2108 | } | ||||
2109 | } | ||||
2110 | } | ||||
2111 | |||||
2112 | /// Parse the value symbol table at either the current parsing location or | ||||
2113 | /// at the given bit offset if provided. | ||||
2114 | Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) { | ||||
2115 | uint64_t CurrentBit; | ||||
2116 | // Pass in the Offset to distinguish between calling for the module-level | ||||
2117 | // VST (where we want to jump to the VST offset) and the function-level | ||||
2118 | // VST (where we don't). | ||||
2119 | if (Offset > 0) { | ||||
2120 | Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); | ||||
2121 | if (!MaybeCurrentBit) | ||||
2122 | return MaybeCurrentBit.takeError(); | ||||
2123 | CurrentBit = MaybeCurrentBit.get(); | ||||
2124 | // If this module uses a string table, read this as a module-level VST. | ||||
2125 | if (UseStrtab) { | ||||
2126 | if (Error Err = parseGlobalValueSymbolTable()) | ||||
2127 | return Err; | ||||
2128 | if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) | ||||
2129 | return JumpFailed; | ||||
2130 | return Error::success(); | ||||
2131 | } | ||||
2132 | // Otherwise, the VST will be in a similar format to a function-level VST, | ||||
2133 | // and will contain symbol names. | ||||
2134 | } | ||||
2135 | |||||
2136 | // Compute the delta between the bitcode indices in the VST (the word offset | ||||
2137 | // to the word-aligned ENTER_SUBBLOCK for the function block, and that | ||||
2138 | // expected by the lazy reader. The reader's EnterSubBlock expects to have | ||||
2139 | // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID | ||||
2140 | // (size BlockIDWidth). Note that we access the stream's AbbrevID width here | ||||
2141 | // just before entering the VST subblock because: 1) the EnterSubBlock | ||||
2142 | // changes the AbbrevID width; 2) the VST block is nested within the same | ||||
2143 | // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same | ||||
2144 | // AbbrevID width before calling EnterSubBlock; and 3) when we want to | ||||
2145 | // jump to the FUNCTION_BLOCK using this offset later, we don't want | ||||
2146 | // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. | ||||
2147 | unsigned FuncBitcodeOffsetDelta = | ||||
2148 | Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; | ||||
2149 | |||||
2150 | if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) | ||||
2151 | return Err; | ||||
2152 | |||||
2153 | SmallVector<uint64_t, 64> Record; | ||||
2154 | |||||
2155 | Triple TT(TheModule->getTargetTriple()); | ||||
2156 | |||||
2157 | // Read all the records for this value table. | ||||
2158 | SmallString<128> ValueName; | ||||
2159 | |||||
2160 | while (true) { | ||||
2161 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
2162 | if (!MaybeEntry) | ||||
2163 | return MaybeEntry.takeError(); | ||||
2164 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
2165 | |||||
2166 | switch (Entry.Kind) { | ||||
2167 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
2168 | case BitstreamEntry::Error: | ||||
2169 | return error("Malformed block"); | ||||
2170 | case BitstreamEntry::EndBlock: | ||||
2171 | if (Offset > 0) | ||||
2172 | if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) | ||||
2173 | return JumpFailed; | ||||
2174 | return Error::success(); | ||||
2175 | case BitstreamEntry::Record: | ||||
2176 | // The interesting case. | ||||
2177 | break; | ||||
2178 | } | ||||
2179 | |||||
2180 | // Read a record. | ||||
2181 | Record.clear(); | ||||
2182 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
2183 | if (!MaybeRecord) | ||||
2184 | return MaybeRecord.takeError(); | ||||
2185 | switch (MaybeRecord.get()) { | ||||
2186 | default: // Default behavior: unknown type. | ||||
2187 | break; | ||||
2188 | case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] | ||||
2189 | Expected<Value *> ValOrErr = recordValue(Record, 1, TT); | ||||
2190 | if (Error Err = ValOrErr.takeError()) | ||||
2191 | return Err; | ||||
2192 | ValOrErr.get(); | ||||
2193 | break; | ||||
2194 | } | ||||
2195 | case bitc::VST_CODE_FNENTRY: { | ||||
2196 | // VST_CODE_FNENTRY: [valueid, offset, namechar x N] | ||||
2197 | Expected<Value *> ValOrErr = recordValue(Record, 2, TT); | ||||
2198 | if (Error Err = ValOrErr.takeError()) | ||||
2199 | return Err; | ||||
2200 | Value *V = ValOrErr.get(); | ||||
2201 | |||||
2202 | // Ignore function offsets emitted for aliases of functions in older | ||||
2203 | // versions of LLVM. | ||||
2204 | if (auto *F = dyn_cast<Function>(V)) | ||||
2205 | setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record); | ||||
2206 | break; | ||||
2207 | } | ||||
2208 | case bitc::VST_CODE_BBENTRY: { | ||||
2209 | if (convertToString(Record, 1, ValueName)) | ||||
2210 | return error("Invalid record"); | ||||
2211 | BasicBlock *BB = getBasicBlock(Record[0]); | ||||
2212 | if (!BB) | ||||
2213 | return error("Invalid record"); | ||||
2214 | |||||
2215 | BB->setName(StringRef(ValueName.data(), ValueName.size())); | ||||
2216 | ValueName.clear(); | ||||
2217 | break; | ||||
2218 | } | ||||
2219 | } | ||||
2220 | } | ||||
2221 | } | ||||
2222 | |||||
2223 | /// Decode a signed value stored with the sign bit in the LSB for dense VBR | ||||
2224 | /// encoding. | ||||
2225 | uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { | ||||
2226 | if ((V & 1) == 0) | ||||
2227 | return V >> 1; | ||||
2228 | if (V != 1) | ||||
2229 | return -(V >> 1); | ||||
2230 | // There is no such thing as -0 with integers. "-0" really means MININT. | ||||
2231 | return 1ULL << 63; | ||||
2232 | } | ||||
2233 | |||||
2234 | /// Resolve all of the initializers for global values and aliases that we can. | ||||
2235 | Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() { | ||||
2236 | std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist; | ||||
2237 | std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> | ||||
2238 | IndirectSymbolInitWorklist; | ||||
2239 | std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist; | ||||
2240 | std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist; | ||||
2241 | std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist; | ||||
2242 | |||||
2243 | GlobalInitWorklist.swap(GlobalInits); | ||||
2244 | IndirectSymbolInitWorklist.swap(IndirectSymbolInits); | ||||
2245 | FunctionPrefixWorklist.swap(FunctionPrefixes); | ||||
2246 | FunctionPrologueWorklist.swap(FunctionPrologues); | ||||
2247 | FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns); | ||||
2248 | |||||
2249 | while (!GlobalInitWorklist.empty()) { | ||||
2250 | unsigned ValID = GlobalInitWorklist.back().second; | ||||
2251 | if (ValID >= ValueList.size()) { | ||||
2252 | // Not ready to resolve this yet, it requires something later in the file. | ||||
2253 | GlobalInits.push_back(GlobalInitWorklist.back()); | ||||
2254 | } else { | ||||
2255 | if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) | ||||
2256 | GlobalInitWorklist.back().first->setInitializer(C); | ||||
2257 | else | ||||
2258 | return error("Expected a constant"); | ||||
2259 | } | ||||
2260 | GlobalInitWorklist.pop_back(); | ||||
2261 | } | ||||
2262 | |||||
2263 | while (!IndirectSymbolInitWorklist.empty()) { | ||||
2264 | unsigned ValID = IndirectSymbolInitWorklist.back().second; | ||||
2265 | if (ValID >= ValueList.size()) { | ||||
2266 | IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back()); | ||||
2267 | } else { | ||||
2268 | Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]); | ||||
2269 | if (!C) | ||||
2270 | return error("Expected a constant"); | ||||
2271 | GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first; | ||||
2272 | if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType()) | ||||
2273 | return error("Alias and aliasee types don't match"); | ||||
2274 | GIS->setIndirectSymbol(C); | ||||
2275 | } | ||||
2276 | IndirectSymbolInitWorklist.pop_back(); | ||||
2277 | } | ||||
2278 | |||||
2279 | while (!FunctionPrefixWorklist.empty()) { | ||||
2280 | unsigned ValID = FunctionPrefixWorklist.back().second; | ||||
2281 | if (ValID >= ValueList.size()) { | ||||
2282 | FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); | ||||
2283 | } else { | ||||
2284 | if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) | ||||
2285 | FunctionPrefixWorklist.back().first->setPrefixData(C); | ||||
2286 | else | ||||
2287 | return error("Expected a constant"); | ||||
2288 | } | ||||
2289 | FunctionPrefixWorklist.pop_back(); | ||||
2290 | } | ||||
2291 | |||||
2292 | while (!FunctionPrologueWorklist.empty()) { | ||||
2293 | unsigned ValID = FunctionPrologueWorklist.back().second; | ||||
2294 | if (ValID >= ValueList.size()) { | ||||
2295 | FunctionPrologues.push_back(FunctionPrologueWorklist.back()); | ||||
2296 | } else { | ||||
2297 | if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) | ||||
2298 | FunctionPrologueWorklist.back().first->setPrologueData(C); | ||||
2299 | else | ||||
2300 | return error("Expected a constant"); | ||||
2301 | } | ||||
2302 | FunctionPrologueWorklist.pop_back(); | ||||
2303 | } | ||||
2304 | |||||
2305 | while (!FunctionPersonalityFnWorklist.empty()) { | ||||
2306 | unsigned ValID = FunctionPersonalityFnWorklist.back().second; | ||||
2307 | if (ValID >= ValueList.size()) { | ||||
2308 | FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back()); | ||||
2309 | } else { | ||||
2310 | if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) | ||||
2311 | FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C); | ||||
2312 | else | ||||
2313 | return error("Expected a constant"); | ||||
2314 | } | ||||
2315 | FunctionPersonalityFnWorklist.pop_back(); | ||||
2316 | } | ||||
2317 | |||||
2318 | return Error::success(); | ||||
2319 | } | ||||
2320 | |||||
2321 | static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { | ||||
2322 | SmallVector<uint64_t, 8> Words(Vals.size()); | ||||
2323 | transform(Vals, Words.begin(), | ||||
2324 | BitcodeReader::decodeSignRotatedValue); | ||||
2325 | |||||
2326 | return APInt(TypeBits, Words); | ||||
2327 | } | ||||
2328 | |||||
2329 | Error BitcodeReader::parseConstants() { | ||||
2330 | if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) | ||||
| |||||
2331 | return Err; | ||||
2332 | |||||
2333 | SmallVector<uint64_t, 64> Record; | ||||
2334 | |||||
2335 | // Read all the records for this value table. | ||||
2336 | Type *CurTy = Type::getInt32Ty(Context); | ||||
2337 | Type *CurFullTy = Type::getInt32Ty(Context); | ||||
2338 | unsigned NextCstNo = ValueList.size(); | ||||
2339 | |||||
2340 | while (true) { | ||||
2341 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
2342 | if (!MaybeEntry) | ||||
2343 | return MaybeEntry.takeError(); | ||||
2344 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
2345 | |||||
2346 | switch (Entry.Kind) { | ||||
2347 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
2348 | case BitstreamEntry::Error: | ||||
2349 | return error("Malformed block"); | ||||
2350 | case BitstreamEntry::EndBlock: | ||||
2351 | if (NextCstNo != ValueList.size()) | ||||
2352 | return error("Invalid constant reference"); | ||||
2353 | |||||
2354 | // Once all the constants have been read, go through and resolve forward | ||||
2355 | // references. | ||||
2356 | ValueList.resolveConstantForwardRefs(); | ||||
2357 | return Error::success(); | ||||
2358 | case BitstreamEntry::Record: | ||||
2359 | // The interesting case. | ||||
2360 | break; | ||||
2361 | } | ||||
2362 | |||||
2363 | // Read a record. | ||||
2364 | Record.clear(); | ||||
2365 | Type *VoidType = Type::getVoidTy(Context); | ||||
2366 | Value *V = nullptr; | ||||
2367 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
2368 | if (!MaybeBitCode) | ||||
2369 | return MaybeBitCode.takeError(); | ||||
2370 | switch (unsigned BitCode = MaybeBitCode.get()) { | ||||
2371 | default: // Default behavior: unknown constant | ||||
2372 | case bitc::CST_CODE_UNDEF: // UNDEF | ||||
2373 | V = UndefValue::get(CurTy); | ||||
2374 | break; | ||||
2375 | case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] | ||||
2376 | if (Record.empty()) | ||||
2377 | return error("Invalid record"); | ||||
2378 | if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) | ||||
2379 | return error("Invalid record"); | ||||
2380 | if (TypeList[Record[0]] == VoidType) | ||||
2381 | return error("Invalid constant type"); | ||||
2382 | CurFullTy = TypeList[Record[0]]; | ||||
2383 | CurTy = flattenPointerTypes(CurFullTy); | ||||
2384 | continue; // Skip the ValueList manipulation. | ||||
2385 | case bitc::CST_CODE_NULL: // NULL | ||||
2386 | if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy()) | ||||
2387 | return error("Invalid type for a constant null value"); | ||||
2388 | V = Constant::getNullValue(CurTy); | ||||
2389 | break; | ||||
2390 | case bitc::CST_CODE_INTEGER: // INTEGER: [intval] | ||||
2391 | if (!CurTy->isIntegerTy() || Record.empty()) | ||||
2392 | return error("Invalid record"); | ||||
2393 | V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); | ||||
2394 | break; | ||||
2395 | case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] | ||||
2396 | if (!CurTy->isIntegerTy() || Record.empty()) | ||||
2397 | return error("Invalid record"); | ||||
2398 | |||||
2399 | APInt VInt = | ||||
2400 | readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); | ||||
2401 | V = ConstantInt::get(Context, VInt); | ||||
2402 | |||||
2403 | break; | ||||
2404 | } | ||||
2405 | case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] | ||||
2406 | if (Record.empty()) | ||||
2407 | return error("Invalid record"); | ||||
2408 | if (CurTy->isHalfTy()) | ||||
2409 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(), | ||||
2410 | APInt(16, (uint16_t)Record[0]))); | ||||
2411 | else if (CurTy->isFloatTy()) | ||||
2412 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(), | ||||
2413 | APInt(32, (uint32_t)Record[0]))); | ||||
2414 | else if (CurTy->isDoubleTy()) | ||||
2415 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(), | ||||
2416 | APInt(64, Record[0]))); | ||||
2417 | else if (CurTy->isX86_FP80Ty()) { | ||||
2418 | // Bits are not stored the same way as a normal i80 APInt, compensate. | ||||
2419 | uint64_t Rearrange[2]; | ||||
2420 | Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); | ||||
2421 | Rearrange[1] = Record[0] >> 48; | ||||
2422 | V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(), | ||||
2423 | APInt(80, Rearrange))); | ||||
2424 | } else if (CurTy->isFP128Ty()) | ||||
2425 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(), | ||||
2426 | APInt(128, Record))); | ||||
2427 | else if (CurTy->isPPC_FP128Ty()) | ||||
2428 | V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(), | ||||
2429 | APInt(128, Record))); | ||||
2430 | else | ||||
2431 | V = UndefValue::get(CurTy); | ||||
2432 | break; | ||||
2433 | } | ||||
2434 | |||||
2435 | case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] | ||||
2436 | if (Record.empty()) | ||||
2437 | return error("Invalid record"); | ||||
2438 | |||||
2439 | unsigned Size = Record.size(); | ||||
2440 | SmallVector<Constant*, 16> Elts; | ||||
2441 | |||||
2442 | if (StructType *STy = dyn_cast<StructType>(CurTy)) { | ||||
2443 | for (unsigned i = 0; i != Size; ++i) | ||||
2444 | Elts.push_back(ValueList.getConstantFwdRef(Record[i], | ||||
2445 | STy->getElementType(i))); | ||||
2446 | V = ConstantStruct::get(STy, Elts); | ||||
2447 | } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { | ||||
2448 | Type *EltTy = ATy->getElementType(); | ||||
2449 | for (unsigned i = 0; i != Size; ++i) | ||||
2450 | Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); | ||||
2451 | V = ConstantArray::get(ATy, Elts); | ||||
2452 | } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { | ||||
2453 | Type *EltTy = VTy->getElementType(); | ||||
2454 | for (unsigned i = 0; i != Size; ++i) | ||||
2455 | Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); | ||||
2456 | V = ConstantVector::get(Elts); | ||||
2457 | } else { | ||||
2458 | V = UndefValue::get(CurTy); | ||||
2459 | } | ||||
2460 | break; | ||||
2461 | } | ||||
2462 | case bitc::CST_CODE_STRING: // STRING: [values] | ||||
2463 | case bitc::CST_CODE_CSTRING: { // CSTRING: [values] | ||||
2464 | if (Record.empty()) | ||||
2465 | return error("Invalid record"); | ||||
2466 | |||||
2467 | SmallString<16> Elts(Record.begin(), Record.end()); | ||||
2468 | V = ConstantDataArray::getString(Context, Elts, | ||||
2469 | BitCode == bitc::CST_CODE_CSTRING); | ||||
2470 | break; | ||||
2471 | } | ||||
2472 | case bitc::CST_CODE_DATA: {// DATA: [n x value] | ||||
2473 | if (Record.empty()) | ||||
2474 | return error("Invalid record"); | ||||
2475 | |||||
2476 | Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); | ||||
2477 | if (EltTy->isIntegerTy(8)) { | ||||
2478 | SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); | ||||
2479 | if (isa<VectorType>(CurTy)) | ||||
2480 | V = ConstantDataVector::get(Context, Elts); | ||||
2481 | else | ||||
2482 | V = ConstantDataArray::get(Context, Elts); | ||||
2483 | } else if (EltTy->isIntegerTy(16)) { | ||||
2484 | SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); | ||||
2485 | if (isa<VectorType>(CurTy)) | ||||
2486 | V = ConstantDataVector::get(Context, Elts); | ||||
2487 | else | ||||
2488 | V = ConstantDataArray::get(Context, Elts); | ||||
2489 | } else if (EltTy->isIntegerTy(32)) { | ||||
2490 | SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); | ||||
2491 | if (isa<VectorType>(CurTy)) | ||||
2492 | V = ConstantDataVector::get(Context, Elts); | ||||
2493 | else | ||||
2494 | V = ConstantDataArray::get(Context, Elts); | ||||
2495 | } else if (EltTy->isIntegerTy(64)) { | ||||
2496 | SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); | ||||
2497 | if (isa<VectorType>(CurTy)) | ||||
2498 | V = ConstantDataVector::get(Context, Elts); | ||||
2499 | else | ||||
2500 | V = ConstantDataArray::get(Context, Elts); | ||||
2501 | } else if (EltTy->isHalfTy()) { | ||||
2502 | SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); | ||||
2503 | if (isa<VectorType>(CurTy)) | ||||
2504 | V = ConstantDataVector::getFP(Context, Elts); | ||||
2505 | else | ||||
2506 | V = ConstantDataArray::getFP(Context, Elts); | ||||
2507 | } else if (EltTy->isFloatTy()) { | ||||
2508 | SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); | ||||
2509 | if (isa<VectorType>(CurTy)) | ||||
2510 | V = ConstantDataVector::getFP(Context, Elts); | ||||
2511 | else | ||||
2512 | V = ConstantDataArray::getFP(Context, Elts); | ||||
2513 | } else if (EltTy->isDoubleTy()) { | ||||
2514 | SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); | ||||
2515 | if (isa<VectorType>(CurTy)) | ||||
2516 | V = ConstantDataVector::getFP(Context, Elts); | ||||
2517 | else | ||||
2518 | V = ConstantDataArray::getFP(Context, Elts); | ||||
2519 | } else { | ||||
2520 | return error("Invalid type for value"); | ||||
2521 | } | ||||
2522 | break; | ||||
2523 | } | ||||
2524 | case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval] | ||||
2525 | if (Record.size() < 2) | ||||
2526 | return error("Invalid record"); | ||||
2527 | int Opc = getDecodedUnaryOpcode(Record[0], CurTy); | ||||
2528 | if (Opc < 0) { | ||||
2529 | V = UndefValue::get(CurTy); // Unknown unop. | ||||
2530 | } else { | ||||
2531 | Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); | ||||
2532 | unsigned Flags = 0; | ||||
2533 | V = ConstantExpr::get(Opc, LHS, Flags); | ||||
2534 | } | ||||
2535 | break; | ||||
2536 | } | ||||
2537 | case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] | ||||
2538 | if (Record.size() < 3) | ||||
2539 | return error("Invalid record"); | ||||
2540 | int Opc = getDecodedBinaryOpcode(Record[0], CurTy); | ||||
2541 | if (Opc < 0) { | ||||
2542 | V = UndefValue::get(CurTy); // Unknown binop. | ||||
2543 | } else { | ||||
2544 | Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); | ||||
2545 | Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); | ||||
2546 | unsigned Flags = 0; | ||||
2547 | if (Record.size() >= 4) { | ||||
2548 | if (Opc == Instruction::Add || | ||||
2549 | Opc == Instruction::Sub || | ||||
2550 | Opc == Instruction::Mul || | ||||
2551 | Opc == Instruction::Shl) { | ||||
2552 | if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) | ||||
2553 | Flags |= OverflowingBinaryOperator::NoSignedWrap; | ||||
2554 | if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) | ||||
2555 | Flags |= OverflowingBinaryOperator::NoUnsignedWrap; | ||||
2556 | } else if (Opc == Instruction::SDiv || | ||||
2557 | Opc == Instruction::UDiv || | ||||
2558 | Opc == Instruction::LShr || | ||||
2559 | Opc == Instruction::AShr) { | ||||
2560 | if (Record[3] & (1 << bitc::PEO_EXACT)) | ||||
2561 | Flags |= SDivOperator::IsExact; | ||||
2562 | } | ||||
2563 | } | ||||
2564 | V = ConstantExpr::get(Opc, LHS, RHS, Flags); | ||||
2565 | } | ||||
2566 | break; | ||||
2567 | } | ||||
2568 | case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] | ||||
2569 | if (Record.size() < 3) | ||||
2570 | return error("Invalid record"); | ||||
2571 | int Opc = getDecodedCastOpcode(Record[0]); | ||||
2572 | if (Opc < 0) { | ||||
2573 | V = UndefValue::get(CurTy); // Unknown cast. | ||||
2574 | } else { | ||||
2575 | Type *OpTy = getTypeByID(Record[1]); | ||||
2576 | if (!OpTy) | ||||
2577 | return error("Invalid record"); | ||||
2578 | Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); | ||||
2579 | V = UpgradeBitCastExpr(Opc, Op, CurTy); | ||||
2580 | if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); | ||||
2581 | } | ||||
2582 | break; | ||||
2583 | } | ||||
2584 | case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] | ||||
2585 | case bitc::CST_CODE_CE_GEP: // [ty, n x operands] | ||||
2586 | case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x | ||||
2587 | // operands] | ||||
2588 | unsigned OpNum = 0; | ||||
2589 | Type *PointeeType = nullptr; | ||||
2590 | if (BitCode
| ||||
2591 | Record.size() % 2) | ||||
2592 | PointeeType = getTypeByID(Record[OpNum++]); | ||||
2593 | |||||
2594 | bool InBounds = false; | ||||
2595 | Optional<unsigned> InRangeIndex; | ||||
2596 | if (BitCode
| ||||
2597 | uint64_t Op = Record[OpNum++]; | ||||
2598 | InBounds = Op & 1; | ||||
2599 | InRangeIndex = Op >> 1; | ||||
2600 | } else if (BitCode
| ||||
2601 | InBounds = true; | ||||
2602 | |||||
2603 | SmallVector<Constant*, 16> Elts; | ||||
2604 | Type *Elt0FullTy = nullptr; | ||||
2605 | while (OpNum != Record.size()) { | ||||
2606 | if (!Elt0FullTy) | ||||
2607 | Elt0FullTy = getFullyStructuredTypeByID(Record[OpNum]); | ||||
2608 | Type *ElTy = getTypeByID(Record[OpNum++]); | ||||
2609 | if (!ElTy) | ||||
2610 | return error("Invalid record"); | ||||
2611 | Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); | ||||
2612 | } | ||||
2613 | |||||
2614 | if (Elts.size() < 1) | ||||
2615 | return error("Invalid gep with no operands"); | ||||
2616 | |||||
2617 | Type *ImplicitPointeeType = | ||||
2618 | getPointerElementFlatType(Elt0FullTy->getScalarType()); | ||||
| |||||
2619 | if (!PointeeType) | ||||
2620 | PointeeType = ImplicitPointeeType; | ||||
2621 | else if (PointeeType != ImplicitPointeeType) | ||||
2622 | return error("Explicit gep operator type does not match pointee type " | ||||
2623 | "of pointer operand"); | ||||
2624 | |||||
2625 | ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); | ||||
2626 | V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, | ||||
2627 | InBounds, InRangeIndex); | ||||
2628 | break; | ||||
2629 | } | ||||
2630 | case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] | ||||
2631 | if (Record.size() < 3) | ||||
2632 | return error("Invalid record"); | ||||
2633 | |||||
2634 | Type *SelectorTy = Type::getInt1Ty(Context); | ||||
2635 | |||||
2636 | // The selector might be an i1, an <n x i1>, or a <vscale x n x i1> | ||||
2637 | // Get the type from the ValueList before getting a forward ref. | ||||
2638 | if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) | ||||
2639 | if (Value *V = ValueList[Record[0]]) | ||||
2640 | if (SelectorTy != V->getType()) | ||||
2641 | SelectorTy = VectorType::get(SelectorTy, | ||||
2642 | VTy->getElementCount()); | ||||
2643 | |||||
2644 | V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], | ||||
2645 | SelectorTy), | ||||
2646 | ValueList.getConstantFwdRef(Record[1],CurTy), | ||||
2647 | ValueList.getConstantFwdRef(Record[2],CurTy)); | ||||
2648 | break; | ||||
2649 | } | ||||
2650 | case bitc::CST_CODE_CE_EXTRACTELT | ||||
2651 | : { // CE_EXTRACTELT: [opty, opval, opty, opval] | ||||
2652 | if (Record.size() < 3) | ||||
2653 | return error("Invalid record"); | ||||
2654 | VectorType *OpTy = | ||||
2655 | dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); | ||||
2656 | if (!OpTy) | ||||
2657 | return error("Invalid record"); | ||||
2658 | Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); | ||||
2659 | Constant *Op1 = nullptr; | ||||
2660 | if (Record.size() == 4) { | ||||
2661 | Type *IdxTy = getTypeByID(Record[2]); | ||||
2662 | if (!IdxTy) | ||||
2663 | return error("Invalid record"); | ||||
2664 | Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); | ||||
2665 | } else // TODO: Remove with llvm 4.0 | ||||
2666 | Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); | ||||
2667 | if (!Op1) | ||||
2668 | return error("Invalid record"); | ||||
2669 | V = ConstantExpr::getExtractElement(Op0, Op1); | ||||
2670 | break; | ||||
2671 | } | ||||
2672 | case bitc::CST_CODE_CE_INSERTELT | ||||
2673 | : { // CE_INSERTELT: [opval, opval, opty, opval] | ||||
2674 | VectorType *OpTy = dyn_cast<VectorType>(CurTy); | ||||
2675 | if (Record.size() < 3 || !OpTy) | ||||
2676 | return error("Invalid record"); | ||||
2677 | Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); | ||||
2678 | Constant *Op1 = ValueList.getConstantFwdRef(Record[1], | ||||
2679 | OpTy->getElementType()); | ||||
2680 | Constant *Op2 = nullptr; | ||||
2681 | if (Record.size() == 4) { | ||||
2682 | Type *IdxTy = getTypeByID(Record[2]); | ||||
2683 | if (!IdxTy) | ||||
2684 | return error("Invalid record"); | ||||
2685 | Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); | ||||
2686 | } else // TODO: Remove with llvm 4.0 | ||||
2687 | Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); | ||||
2688 | if (!Op2) | ||||
2689 | return error("Invalid record"); | ||||
2690 | V = ConstantExpr::getInsertElement(Op0, Op1, Op2); | ||||
2691 | break; | ||||
2692 | } | ||||
2693 | case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] | ||||
2694 | VectorType *OpTy = dyn_cast<VectorType>(CurTy); | ||||
2695 | if (Record.size() < 3 || !OpTy) | ||||
2696 | return error("Invalid record"); | ||||
2697 | Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); | ||||
2698 | Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); | ||||
2699 | Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), | ||||
2700 | OpTy->getElementCount()); | ||||
2701 | Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); | ||||
2702 | V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); | ||||
2703 | break; | ||||
2704 | } | ||||
2705 | case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] | ||||
2706 | VectorType *RTy = dyn_cast<VectorType>(CurTy); | ||||
2707 | VectorType *OpTy = | ||||
2708 | dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); | ||||
2709 | if (Record.size() < 4 || !RTy || !OpTy) | ||||
2710 | return error("Invalid record"); | ||||
2711 | Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); | ||||
2712 | Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); | ||||
2713 | Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), | ||||
2714 | RTy->getElementCount()); | ||||
2715 | Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); | ||||
2716 | V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); | ||||
2717 | break; | ||||
2718 | } | ||||
2719 | case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] | ||||
2720 | if (Record.size() < 4) | ||||
2721 | return error("Invalid record"); | ||||
2722 | Type *OpTy = getTypeByID(Record[0]); | ||||
2723 | if (!OpTy) | ||||
2724 | return error("Invalid record"); | ||||
2725 | Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); | ||||
2726 | Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); | ||||
2727 | |||||
2728 | if (OpTy->isFPOrFPVectorTy()) | ||||
2729 | V = ConstantExpr::getFCmp(Record[3], Op0, Op1); | ||||
2730 | else | ||||
2731 | V = ConstantExpr::getICmp(Record[3], Op0, Op1); | ||||
2732 | break; | ||||
2733 | } | ||||
2734 | // This maintains backward compatibility, pre-asm dialect keywords. | ||||
2735 | // FIXME: Remove with the 4.0 release. | ||||
2736 | case bitc::CST_CODE_INLINEASM_OLD: { | ||||
2737 | if (Record.size() < 2) | ||||
2738 | return error("Invalid record"); | ||||
2739 | std::string AsmStr, ConstrStr; | ||||
2740 | bool HasSideEffects = Record[0] & 1; | ||||
2741 | bool IsAlignStack = Record[0] >> 1; | ||||
2742 | unsigned AsmStrSize = Record[1]; | ||||
2743 | if (2+AsmStrSize >= Record.size()) | ||||
2744 | return error("Invalid record"); | ||||
2745 | unsigned ConstStrSize = Record[2+AsmStrSize]; | ||||
2746 | if (3+AsmStrSize+ConstStrSize > Record.size()) | ||||
2747 | return error("Invalid record"); | ||||
2748 | |||||
2749 | for (unsigned i = 0; i != AsmStrSize; ++i) | ||||
2750 | AsmStr += (char)Record[2+i]; | ||||
2751 | for (unsigned i = 0; i != ConstStrSize; ++i) | ||||
2752 | ConstrStr += (char)Record[3+AsmStrSize+i]; | ||||
2753 | UpgradeInlineAsmString(&AsmStr); | ||||
2754 | V = InlineAsm::get( | ||||
2755 | cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr, | ||||
2756 | ConstrStr, HasSideEffects, IsAlignStack); | ||||
2757 | break; | ||||
2758 | } | ||||
2759 | // This version adds support for the asm dialect keywords (e.g., | ||||
2760 | // inteldialect). | ||||
2761 | case bitc::CST_CODE_INLINEASM: { | ||||
2762 | if (Record.size() < 2) | ||||
2763 | return error("Invalid record"); | ||||
2764 | std::string AsmStr, ConstrStr; | ||||
2765 | bool HasSideEffects = Record[0] & 1; | ||||
2766 | bool IsAlignStack = (Record[0] >> 1) & 1; | ||||
2767 | unsigned AsmDialect = Record[0] >> 2; | ||||
2768 | unsigned AsmStrSize = Record[1]; | ||||
2769 | if (2+AsmStrSize >= Record.size()) | ||||
2770 | return error("Invalid record"); | ||||
2771 | unsigned ConstStrSize = Record[2+AsmStrSize]; | ||||
2772 | if (3+AsmStrSize+ConstStrSize > Record.size()) | ||||
2773 | return error("Invalid record"); | ||||
2774 | |||||
2775 | for (unsigned i = 0; i != AsmStrSize; ++i) | ||||
2776 | AsmStr += (char)Record[2+i]; | ||||
2777 | for (unsigned i = 0; i != ConstStrSize; ++i) | ||||
2778 | ConstrStr += (char)Record[3+AsmStrSize+i]; | ||||
2779 | UpgradeInlineAsmString(&AsmStr); | ||||
2780 | V = InlineAsm::get( | ||||
2781 | cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr, | ||||
2782 | ConstrStr, HasSideEffects, IsAlignStack, | ||||
2783 | InlineAsm::AsmDialect(AsmDialect)); | ||||
2784 | break; | ||||
2785 | } | ||||
2786 | case bitc::CST_CODE_BLOCKADDRESS:{ | ||||
2787 | if (Record.size() < 3) | ||||
2788 | return error("Invalid record"); | ||||
2789 | Type *FnTy = getTypeByID(Record[0]); | ||||
2790 | if (!FnTy) | ||||
2791 | return error("Invalid record"); | ||||
2792 | Function *Fn = | ||||
2793 | dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); | ||||
2794 | if (!Fn) | ||||
2795 | return error("Invalid record"); | ||||
2796 | |||||
2797 | // If the function is already parsed we can insert the block address right | ||||
2798 | // away. | ||||
2799 | BasicBlock *BB; | ||||
2800 | unsigned BBID = Record[2]; | ||||
2801 | if (!BBID) | ||||
2802 | // Invalid reference to entry block. | ||||
2803 | return error("Invalid ID"); | ||||
2804 | if (!Fn->empty()) { | ||||
2805 | Function::iterator BBI = Fn->begin(), BBE = Fn->end(); | ||||
2806 | for (size_t I = 0, E = BBID; I != E; ++I) { | ||||
2807 | if (BBI == BBE) | ||||
2808 | return error("Invalid ID"); | ||||
2809 | ++BBI; | ||||
2810 | } | ||||
2811 | BB = &*BBI; | ||||
2812 | } else { | ||||
2813 | // Otherwise insert a placeholder and remember it so it can be inserted | ||||
2814 | // when the function is parsed. | ||||
2815 | auto &FwdBBs = BasicBlockFwdRefs[Fn]; | ||||
2816 | if (FwdBBs.empty()) | ||||
2817 | BasicBlockFwdRefQueue.push_back(Fn); | ||||
2818 | if (FwdBBs.size() < BBID + 1) | ||||
2819 | FwdBBs.resize(BBID + 1); | ||||
2820 | if (!FwdBBs[BBID]) | ||||
2821 | FwdBBs[BBID] = BasicBlock::Create(Context); | ||||
2822 | BB = FwdBBs[BBID]; | ||||
2823 | } | ||||
2824 | V = BlockAddress::get(Fn, BB); | ||||
2825 | break; | ||||
2826 | } | ||||
2827 | } | ||||
2828 | |||||
2829 | assert(V->getType() == flattenPointerTypes(CurFullTy) &&((V->getType() == flattenPointerTypes(CurFullTy) && "Incorrect fully structured type provided for Constant") ? static_cast <void> (0) : __assert_fail ("V->getType() == flattenPointerTypes(CurFullTy) && \"Incorrect fully structured type provided for Constant\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 2830, __PRETTY_FUNCTION__)) | ||||
2830 | "Incorrect fully structured type provided for Constant")((V->getType() == flattenPointerTypes(CurFullTy) && "Incorrect fully structured type provided for Constant") ? static_cast <void> (0) : __assert_fail ("V->getType() == flattenPointerTypes(CurFullTy) && \"Incorrect fully structured type provided for Constant\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 2830, __PRETTY_FUNCTION__)); | ||||
2831 | ValueList.assignValue(V, NextCstNo, CurFullTy); | ||||
2832 | ++NextCstNo; | ||||
2833 | } | ||||
2834 | } | ||||
2835 | |||||
2836 | Error BitcodeReader::parseUseLists() { | ||||
2837 | if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) | ||||
2838 | return Err; | ||||
2839 | |||||
2840 | // Read all the records. | ||||
2841 | SmallVector<uint64_t, 64> Record; | ||||
2842 | |||||
2843 | while (true) { | ||||
2844 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
2845 | if (!MaybeEntry) | ||||
2846 | return MaybeEntry.takeError(); | ||||
2847 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
2848 | |||||
2849 | switch (Entry.Kind) { | ||||
2850 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
2851 | case BitstreamEntry::Error: | ||||
2852 | return error("Malformed block"); | ||||
2853 | case BitstreamEntry::EndBlock: | ||||
2854 | return Error::success(); | ||||
2855 | case BitstreamEntry::Record: | ||||
2856 | // The interesting case. | ||||
2857 | break; | ||||
2858 | } | ||||
2859 | |||||
2860 | // Read a use list record. | ||||
2861 | Record.clear(); | ||||
2862 | bool IsBB = false; | ||||
2863 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
2864 | if (!MaybeRecord) | ||||
2865 | return MaybeRecord.takeError(); | ||||
2866 | switch (MaybeRecord.get()) { | ||||
2867 | default: // Default behavior: unknown type. | ||||
2868 | break; | ||||
2869 | case bitc::USELIST_CODE_BB: | ||||
2870 | IsBB = true; | ||||
2871 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
2872 | case bitc::USELIST_CODE_DEFAULT: { | ||||
2873 | unsigned RecordLength = Record.size(); | ||||
2874 | if (RecordLength < 3) | ||||
2875 | // Records should have at least an ID and two indexes. | ||||
2876 | return error("Invalid record"); | ||||
2877 | unsigned ID = Record.back(); | ||||
2878 | Record.pop_back(); | ||||
2879 | |||||
2880 | Value *V; | ||||
2881 | if (IsBB) { | ||||
2882 | assert(ID < FunctionBBs.size() && "Basic block not found")((ID < FunctionBBs.size() && "Basic block not found" ) ? static_cast<void> (0) : __assert_fail ("ID < FunctionBBs.size() && \"Basic block not found\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 2882, __PRETTY_FUNCTION__)); | ||||
2883 | V = FunctionBBs[ID]; | ||||
2884 | } else | ||||
2885 | V = ValueList[ID]; | ||||
2886 | unsigned NumUses = 0; | ||||
2887 | SmallDenseMap<const Use *, unsigned, 16> Order; | ||||
2888 | for (const Use &U : V->materialized_uses()) { | ||||
2889 | if (++NumUses > Record.size()) | ||||
2890 | break; | ||||
2891 | Order[&U] = Record[NumUses - 1]; | ||||
2892 | } | ||||
2893 | if (Order.size() != Record.size() || NumUses > Record.size()) | ||||
2894 | // Mismatches can happen if the functions are being materialized lazily | ||||
2895 | // (out-of-order), or a value has been upgraded. | ||||
2896 | break; | ||||
2897 | |||||
2898 | V->sortUseList([&](const Use &L, const Use &R) { | ||||
2899 | return Order.lookup(&L) < Order.lookup(&R); | ||||
2900 | }); | ||||
2901 | break; | ||||
2902 | } | ||||
2903 | } | ||||
2904 | } | ||||
2905 | } | ||||
2906 | |||||
2907 | /// When we see the block for metadata, remember where it is and then skip it. | ||||
2908 | /// This lets us lazily deserialize the metadata. | ||||
2909 | Error BitcodeReader::rememberAndSkipMetadata() { | ||||
2910 | // Save the current stream state. | ||||
2911 | uint64_t CurBit = Stream.GetCurrentBitNo(); | ||||
2912 | DeferredMetadataInfo.push_back(CurBit); | ||||
2913 | |||||
2914 | // Skip over the block for now. | ||||
2915 | if (Error Err = Stream.SkipBlock()) | ||||
2916 | return Err; | ||||
2917 | return Error::success(); | ||||
2918 | } | ||||
2919 | |||||
2920 | Error BitcodeReader::materializeMetadata() { | ||||
2921 | for (uint64_t BitPos : DeferredMetadataInfo) { | ||||
2922 | // Move the bit stream to the saved position. | ||||
2923 | if (Error JumpFailed = Stream.JumpToBit(BitPos)) | ||||
2924 | return JumpFailed; | ||||
2925 | if (Error Err = MDLoader->parseModuleMetadata()) | ||||
2926 | return Err; | ||||
2927 | } | ||||
2928 | |||||
2929 | // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level | ||||
2930 | // metadata. | ||||
2931 | if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) { | ||||
2932 | NamedMDNode *LinkerOpts = | ||||
2933 | TheModule->getOrInsertNamedMetadata("llvm.linker.options"); | ||||
2934 | for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands()) | ||||
2935 | LinkerOpts->addOperand(cast<MDNode>(MDOptions)); | ||||
2936 | } | ||||
2937 | |||||
2938 | DeferredMetadataInfo.clear(); | ||||
2939 | return Error::success(); | ||||
2940 | } | ||||
2941 | |||||
2942 | void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } | ||||
2943 | |||||
2944 | /// When we see the block for a function body, remember where it is and then | ||||
2945 | /// skip it. This lets us lazily deserialize the functions. | ||||
2946 | Error BitcodeReader::rememberAndSkipFunctionBody() { | ||||
2947 | // Get the function we are talking about. | ||||
2948 | if (FunctionsWithBodies.empty()) | ||||
2949 | return error("Insufficient function protos"); | ||||
2950 | |||||
2951 | Function *Fn = FunctionsWithBodies.back(); | ||||
2952 | FunctionsWithBodies.pop_back(); | ||||
2953 | |||||
2954 | // Save the current stream state. | ||||
2955 | uint64_t CurBit = Stream.GetCurrentBitNo(); | ||||
2956 | assert((((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && "Mismatch between VST and scanned function offsets" ) ? static_cast<void> (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 2958, __PRETTY_FUNCTION__)) | ||||
2957 | (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&(((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && "Mismatch between VST and scanned function offsets" ) ? static_cast<void> (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 2958, __PRETTY_FUNCTION__)) | ||||
2958 | "Mismatch between VST and scanned function offsets")(((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && "Mismatch between VST and scanned function offsets" ) ? static_cast<void> (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 2958, __PRETTY_FUNCTION__)); | ||||
2959 | DeferredFunctionInfo[Fn] = CurBit; | ||||
2960 | |||||
2961 | // Skip over the function block for now. | ||||
2962 | if (Error Err = Stream.SkipBlock()) | ||||
2963 | return Err; | ||||
2964 | return Error::success(); | ||||
2965 | } | ||||
2966 | |||||
2967 | Error BitcodeReader::globalCleanup() { | ||||
2968 | // Patch the initializers for globals and aliases up. | ||||
2969 | if (Error Err = resolveGlobalAndIndirectSymbolInits()) | ||||
2970 | return Err; | ||||
2971 | if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) | ||||
2972 | return error("Malformed global initializer set"); | ||||
2973 | |||||
2974 | // Look for intrinsic functions which need to be upgraded at some point | ||||
2975 | for (Function &F : *TheModule) { | ||||
2976 | MDLoader->upgradeDebugIntrinsics(F); | ||||
2977 | Function *NewFn; | ||||
2978 | if (UpgradeIntrinsicFunction(&F, NewFn)) | ||||
2979 | UpgradedIntrinsics[&F] = NewFn; | ||||
2980 | else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) | ||||
2981 | // Some types could be renamed during loading if several modules are | ||||
2982 | // loaded in the same LLVMContext (LTO scenario). In this case we should | ||||
2983 | // remangle intrinsics names as well. | ||||
2984 | RemangledIntrinsics[&F] = Remangled.getValue(); | ||||
2985 | } | ||||
2986 | |||||
2987 | // Look for global variables which need to be renamed. | ||||
2988 | std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables; | ||||
2989 | for (GlobalVariable &GV : TheModule->globals()) | ||||
2990 | if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV)) | ||||
2991 | UpgradedVariables.emplace_back(&GV, Upgraded); | ||||
2992 | for (auto &Pair : UpgradedVariables) { | ||||
2993 | Pair.first->eraseFromParent(); | ||||
2994 | TheModule->getGlobalList().push_back(Pair.second); | ||||
2995 | } | ||||
2996 | |||||
2997 | // Force deallocation of memory for these vectors to favor the client that | ||||
2998 | // want lazy deserialization. | ||||
2999 | std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits); | ||||
3000 | std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap( | ||||
3001 | IndirectSymbolInits); | ||||
3002 | return Error::success(); | ||||
3003 | } | ||||
3004 | |||||
3005 | /// Support for lazy parsing of function bodies. This is required if we | ||||
3006 | /// either have an old bitcode file without a VST forward declaration record, | ||||
3007 | /// or if we have an anonymous function being materialized, since anonymous | ||||
3008 | /// functions do not have a name and are therefore not in the VST. | ||||
3009 | Error BitcodeReader::rememberAndSkipFunctionBodies() { | ||||
3010 | if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit)) | ||||
3011 | return JumpFailed; | ||||
3012 | |||||
3013 | if (Stream.AtEndOfStream()) | ||||
3014 | return error("Could not find function in stream"); | ||||
3015 | |||||
3016 | if (!SeenFirstFunctionBody) | ||||
3017 | return error("Trying to materialize functions before seeing function blocks"); | ||||
3018 | |||||
3019 | // An old bitcode file with the symbol table at the end would have | ||||
3020 | // finished the parse greedily. | ||||
3021 | assert(SeenValueSymbolTable)((SeenValueSymbolTable) ? static_cast<void> (0) : __assert_fail ("SeenValueSymbolTable", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3021, __PRETTY_FUNCTION__)); | ||||
3022 | |||||
3023 | SmallVector<uint64_t, 64> Record; | ||||
3024 | |||||
3025 | while (true) { | ||||
3026 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
3027 | if (!MaybeEntry) | ||||
3028 | return MaybeEntry.takeError(); | ||||
3029 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
3030 | |||||
3031 | switch (Entry.Kind) { | ||||
3032 | default: | ||||
3033 | return error("Expect SubBlock"); | ||||
3034 | case BitstreamEntry::SubBlock: | ||||
3035 | switch (Entry.ID) { | ||||
3036 | default: | ||||
3037 | return error("Expect function block"); | ||||
3038 | case bitc::FUNCTION_BLOCK_ID: | ||||
3039 | if (Error Err = rememberAndSkipFunctionBody()) | ||||
3040 | return Err; | ||||
3041 | NextUnreadBit = Stream.GetCurrentBitNo(); | ||||
3042 | return Error::success(); | ||||
3043 | } | ||||
3044 | } | ||||
3045 | } | ||||
3046 | } | ||||
3047 | |||||
3048 | bool BitcodeReaderBase::readBlockInfo() { | ||||
3049 | Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo = | ||||
3050 | Stream.ReadBlockInfoBlock(); | ||||
3051 | if (!MaybeNewBlockInfo) | ||||
3052 | return true; // FIXME Handle the error. | ||||
3053 | Optional<BitstreamBlockInfo> NewBlockInfo = | ||||
3054 | std::move(MaybeNewBlockInfo.get()); | ||||
3055 | if (!NewBlockInfo) | ||||
3056 | return true; | ||||
3057 | BlockInfo = std::move(*NewBlockInfo); | ||||
3058 | return false; | ||||
3059 | } | ||||
3060 | |||||
3061 | Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { | ||||
3062 | // v1: [selection_kind, name] | ||||
3063 | // v2: [strtab_offset, strtab_size, selection_kind] | ||||
3064 | StringRef Name; | ||||
3065 | std::tie(Name, Record) = readNameFromStrtab(Record); | ||||
3066 | |||||
3067 | if (Record.empty()) | ||||
3068 | return error("Invalid record"); | ||||
3069 | Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); | ||||
3070 | std::string OldFormatName; | ||||
3071 | if (!UseStrtab) { | ||||
3072 | if (Record.size() < 2) | ||||
3073 | return error("Invalid record"); | ||||
3074 | unsigned ComdatNameSize = Record[1]; | ||||
3075 | OldFormatName.reserve(ComdatNameSize); | ||||
3076 | for (unsigned i = 0; i != ComdatNameSize; ++i) | ||||
3077 | OldFormatName += (char)Record[2 + i]; | ||||
3078 | Name = OldFormatName; | ||||
3079 | } | ||||
3080 | Comdat *C = TheModule->getOrInsertComdat(Name); | ||||
3081 | C->setSelectionKind(SK); | ||||
3082 | ComdatList.push_back(C); | ||||
3083 | return Error::success(); | ||||
3084 | } | ||||
3085 | |||||
3086 | static void inferDSOLocal(GlobalValue *GV) { | ||||
3087 | // infer dso_local from linkage and visibility if it is not encoded. | ||||
3088 | if (GV->hasLocalLinkage() || | ||||
3089 | (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())) | ||||
3090 | GV->setDSOLocal(true); | ||||
3091 | } | ||||
3092 | |||||
3093 | Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { | ||||
3094 | // v1: [pointer type, isconst, initid, linkage, alignment, section, | ||||
3095 | // visibility, threadlocal, unnamed_addr, externally_initialized, | ||||
3096 | // dllstorageclass, comdat, attributes, preemption specifier, | ||||
3097 | // partition strtab offset, partition strtab size] (name in VST) | ||||
3098 | // v2: [strtab_offset, strtab_size, v1] | ||||
3099 | StringRef Name; | ||||
3100 | std::tie(Name, Record) = readNameFromStrtab(Record); | ||||
3101 | |||||
3102 | if (Record.size() < 6) | ||||
3103 | return error("Invalid record"); | ||||
3104 | Type *FullTy = getFullyStructuredTypeByID(Record[0]); | ||||
3105 | Type *Ty = flattenPointerTypes(FullTy); | ||||
3106 | if (!Ty) | ||||
3107 | return error("Invalid record"); | ||||
3108 | bool isConstant = Record[1] & 1; | ||||
3109 | bool explicitType = Record[1] & 2; | ||||
3110 | unsigned AddressSpace; | ||||
3111 | if (explicitType) { | ||||
3112 | AddressSpace = Record[1] >> 2; | ||||
3113 | } else { | ||||
3114 | if (!Ty->isPointerTy()) | ||||
3115 | return error("Invalid type for value"); | ||||
3116 | AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); | ||||
3117 | std::tie(FullTy, Ty) = getPointerElementTypes(FullTy); | ||||
3118 | } | ||||
3119 | |||||
3120 | uint64_t RawLinkage = Record[3]; | ||||
3121 | GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); | ||||
3122 | MaybeAlign Alignment; | ||||
3123 | if (Error Err = parseAlignmentValue(Record[4], Alignment)) | ||||
3124 | return Err; | ||||
3125 | std::string Section; | ||||
3126 | if (Record[5]) { | ||||
3127 | if (Record[5] - 1 >= SectionTable.size()) | ||||
3128 | return error("Invalid ID"); | ||||
3129 | Section = SectionTable[Record[5] - 1]; | ||||
3130 | } | ||||
3131 | GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; | ||||
3132 | // Local linkage must have default visibility. | ||||
3133 | if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) | ||||
3134 | // FIXME: Change to an error if non-default in 4.0. | ||||
3135 | Visibility = getDecodedVisibility(Record[6]); | ||||
3136 | |||||
3137 | GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; | ||||
3138 | if (Record.size() > 7) | ||||
3139 | TLM = getDecodedThreadLocalMode(Record[7]); | ||||
3140 | |||||
3141 | GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; | ||||
3142 | if (Record.size() > 8) | ||||
3143 | UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); | ||||
3144 | |||||
3145 | bool ExternallyInitialized = false; | ||||
3146 | if (Record.size() > 9) | ||||
3147 | ExternallyInitialized = Record[9]; | ||||
3148 | |||||
3149 | GlobalVariable *NewGV = | ||||
3150 | new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name, | ||||
3151 | nullptr, TLM, AddressSpace, ExternallyInitialized); | ||||
3152 | NewGV->setAlignment(Alignment); | ||||
3153 | if (!Section.empty()) | ||||
3154 | NewGV->setSection(Section); | ||||
3155 | NewGV->setVisibility(Visibility); | ||||
3156 | NewGV->setUnnamedAddr(UnnamedAddr); | ||||
3157 | |||||
3158 | if (Record.size() > 10) | ||||
3159 | NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); | ||||
3160 | else | ||||
3161 | upgradeDLLImportExportLinkage(NewGV, RawLinkage); | ||||
3162 | |||||
3163 | FullTy = PointerType::get(FullTy, AddressSpace); | ||||
3164 | assert(NewGV->getType() == flattenPointerTypes(FullTy) &&((NewGV->getType() == flattenPointerTypes(FullTy) && "Incorrect fully specified type for GlobalVariable") ? static_cast <void> (0) : __assert_fail ("NewGV->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully specified type for GlobalVariable\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3165, __PRETTY_FUNCTION__)) | ||||
3165 | "Incorrect fully specified type for GlobalVariable")((NewGV->getType() == flattenPointerTypes(FullTy) && "Incorrect fully specified type for GlobalVariable") ? static_cast <void> (0) : __assert_fail ("NewGV->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully specified type for GlobalVariable\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3165, __PRETTY_FUNCTION__)); | ||||
3166 | ValueList.push_back(NewGV, FullTy); | ||||
3167 | |||||
3168 | // Remember which value to use for the global initializer. | ||||
3169 | if (unsigned InitID = Record[2]) | ||||
3170 | GlobalInits.push_back(std::make_pair(NewGV, InitID - 1)); | ||||
3171 | |||||
3172 | if (Record.size() > 11) { | ||||
3173 | if (unsigned ComdatID = Record[11]) { | ||||
3174 | if (ComdatID > ComdatList.size()) | ||||
3175 | return error("Invalid global variable comdat ID"); | ||||
3176 | NewGV->setComdat(ComdatList[ComdatID - 1]); | ||||
3177 | } | ||||
3178 | } else if (hasImplicitComdat(RawLinkage)) { | ||||
3179 | NewGV->setComdat(reinterpret_cast<Comdat *>(1)); | ||||
3180 | } | ||||
3181 | |||||
3182 | if (Record.size() > 12) { | ||||
3183 | auto AS = getAttributes(Record[12]).getFnAttributes(); | ||||
3184 | NewGV->setAttributes(AS); | ||||
3185 | } | ||||
3186 | |||||
3187 | if (Record.size() > 13) { | ||||
3188 | NewGV->setDSOLocal(getDecodedDSOLocal(Record[13])); | ||||
3189 | } | ||||
3190 | inferDSOLocal(NewGV); | ||||
3191 | |||||
3192 | // Check whether we have enough values to read a partition name. | ||||
3193 | if (Record.size() > 15) | ||||
3194 | NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15])); | ||||
3195 | |||||
3196 | return Error::success(); | ||||
3197 | } | ||||
3198 | |||||
3199 | Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) { | ||||
3200 | // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section, | ||||
3201 | // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat, | ||||
3202 | // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST) | ||||
3203 | // v2: [strtab_offset, strtab_size, v1] | ||||
3204 | StringRef Name; | ||||
3205 | std::tie(Name, Record) = readNameFromStrtab(Record); | ||||
3206 | |||||
3207 | if (Record.size() < 8) | ||||
3208 | return error("Invalid record"); | ||||
3209 | Type *FullFTy = getFullyStructuredTypeByID(Record[0]); | ||||
3210 | Type *FTy = flattenPointerTypes(FullFTy); | ||||
3211 | if (!FTy) | ||||
3212 | return error("Invalid record"); | ||||
3213 | if (isa<PointerType>(FTy)) | ||||
3214 | std::tie(FullFTy, FTy) = getPointerElementTypes(FullFTy); | ||||
3215 | |||||
3216 | if (!isa<FunctionType>(FTy)) | ||||
3217 | return error("Invalid type for value"); | ||||
3218 | auto CC = static_cast<CallingConv::ID>(Record[1]); | ||||
3219 | if (CC & ~CallingConv::MaxID) | ||||
3220 | return error("Invalid calling convention ID"); | ||||
3221 | |||||
3222 | unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace(); | ||||
3223 | if (Record.size() > 16) | ||||
3224 | AddrSpace = Record[16]; | ||||
3225 | |||||
3226 | Function *Func = | ||||
3227 | Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage, | ||||
3228 | AddrSpace, Name, TheModule); | ||||
3229 | |||||
3230 | assert(Func->getFunctionType() == flattenPointerTypes(FullFTy) &&((Func->getFunctionType() == flattenPointerTypes(FullFTy) && "Incorrect fully specified type provided for function") ? static_cast <void> (0) : __assert_fail ("Func->getFunctionType() == flattenPointerTypes(FullFTy) && \"Incorrect fully specified type provided for function\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3231, __PRETTY_FUNCTION__)) | ||||
3231 | "Incorrect fully specified type provided for function")((Func->getFunctionType() == flattenPointerTypes(FullFTy) && "Incorrect fully specified type provided for function") ? static_cast <void> (0) : __assert_fail ("Func->getFunctionType() == flattenPointerTypes(FullFTy) && \"Incorrect fully specified type provided for function\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3231, __PRETTY_FUNCTION__)); | ||||
3232 | FunctionTypes[Func] = cast<FunctionType>(FullFTy); | ||||
3233 | |||||
3234 | Func->setCallingConv(CC); | ||||
3235 | bool isProto = Record[2]; | ||||
3236 | uint64_t RawLinkage = Record[3]; | ||||
3237 | Func->setLinkage(getDecodedLinkage(RawLinkage)); | ||||
3238 | Func->setAttributes(getAttributes(Record[4])); | ||||
3239 | |||||
3240 | // Upgrade any old-style byval without a type by propagating the argument's | ||||
3241 | // pointee type. There should be no opaque pointers where the byval type is | ||||
3242 | // implicit. | ||||
3243 | for (unsigned i = 0; i != Func->arg_size(); ++i) { | ||||
3244 | if (!Func->hasParamAttribute(i, Attribute::ByVal)) | ||||
3245 | continue; | ||||
3246 | |||||
3247 | Type *PTy = cast<FunctionType>(FullFTy)->getParamType(i); | ||||
3248 | Func->removeParamAttr(i, Attribute::ByVal); | ||||
3249 | Func->addParamAttr(i, Attribute::getWithByValType( | ||||
3250 | Context, getPointerElementFlatType(PTy))); | ||||
3251 | } | ||||
3252 | |||||
3253 | MaybeAlign Alignment; | ||||
3254 | if (Error Err = parseAlignmentValue(Record[5], Alignment)) | ||||
3255 | return Err; | ||||
3256 | Func->setAlignment(Alignment); | ||||
3257 | if (Record[6]) { | ||||
3258 | if (Record[6] - 1 >= SectionTable.size()) | ||||
3259 | return error("Invalid ID"); | ||||
3260 | Func->setSection(SectionTable[Record[6] - 1]); | ||||
3261 | } | ||||
3262 | // Local linkage must have default visibility. | ||||
3263 | if (!Func->hasLocalLinkage()) | ||||
3264 | // FIXME: Change to an error if non-default in 4.0. | ||||
3265 | Func->setVisibility(getDecodedVisibility(Record[7])); | ||||
3266 | if (Record.size() > 8 && Record[8]) { | ||||
3267 | if (Record[8] - 1 >= GCTable.size()) | ||||
3268 | return error("Invalid ID"); | ||||
3269 | Func->setGC(GCTable[Record[8] - 1]); | ||||
3270 | } | ||||
3271 | GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; | ||||
3272 | if (Record.size() > 9) | ||||
3273 | UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); | ||||
3274 | Func->setUnnamedAddr(UnnamedAddr); | ||||
3275 | if (Record.size() > 10 && Record[10] != 0) | ||||
3276 | FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1)); | ||||
3277 | |||||
3278 | if (Record.size() > 11) | ||||
3279 | Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); | ||||
3280 | else | ||||
3281 | upgradeDLLImportExportLinkage(Func, RawLinkage); | ||||
3282 | |||||
3283 | if (Record.size() > 12) { | ||||
3284 | if (unsigned ComdatID = Record[12]) { | ||||
3285 | if (ComdatID > ComdatList.size()) | ||||
3286 | return error("Invalid function comdat ID"); | ||||
3287 | Func->setComdat(ComdatList[ComdatID - 1]); | ||||
3288 | } | ||||
3289 | } else if (hasImplicitComdat(RawLinkage)) { | ||||
3290 | Func->setComdat(reinterpret_cast<Comdat *>(1)); | ||||
3291 | } | ||||
3292 | |||||
3293 | if (Record.size() > 13 && Record[13] != 0) | ||||
3294 | FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1)); | ||||
3295 | |||||
3296 | if (Record.size() > 14 && Record[14] != 0) | ||||
3297 | FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); | ||||
3298 | |||||
3299 | if (Record.size() > 15) { | ||||
3300 | Func->setDSOLocal(getDecodedDSOLocal(Record[15])); | ||||
3301 | } | ||||
3302 | inferDSOLocal(Func); | ||||
3303 | |||||
3304 | // Record[16] is the address space number. | ||||
3305 | |||||
3306 | // Check whether we have enough values to read a partition name. | ||||
3307 | if (Record.size() > 18) | ||||
3308 | Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18])); | ||||
3309 | |||||
3310 | Type *FullTy = PointerType::get(FullFTy, AddrSpace); | ||||
3311 | assert(Func->getType() == flattenPointerTypes(FullTy) &&((Func->getType() == flattenPointerTypes(FullTy) && "Incorrect fully specified type provided for Function") ? static_cast <void> (0) : __assert_fail ("Func->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully specified type provided for Function\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3312, __PRETTY_FUNCTION__)) | ||||
3312 | "Incorrect fully specified type provided for Function")((Func->getType() == flattenPointerTypes(FullTy) && "Incorrect fully specified type provided for Function") ? static_cast <void> (0) : __assert_fail ("Func->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully specified type provided for Function\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3312, __PRETTY_FUNCTION__)); | ||||
3313 | ValueList.push_back(Func, FullTy); | ||||
3314 | |||||
3315 | // If this is a function with a body, remember the prototype we are | ||||
3316 | // creating now, so that we can match up the body with them later. | ||||
3317 | if (!isProto) { | ||||
3318 | Func->setIsMaterializable(true); | ||||
3319 | FunctionsWithBodies.push_back(Func); | ||||
3320 | DeferredFunctionInfo[Func] = 0; | ||||
3321 | } | ||||
3322 | return Error::success(); | ||||
3323 | } | ||||
3324 | |||||
3325 | Error BitcodeReader::parseGlobalIndirectSymbolRecord( | ||||
3326 | unsigned BitCode, ArrayRef<uint64_t> Record) { | ||||
3327 | // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST) | ||||
3328 | // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, | ||||
3329 | // dllstorageclass, threadlocal, unnamed_addr, | ||||
3330 | // preemption specifier] (name in VST) | ||||
3331 | // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage, | ||||
3332 | // visibility, dllstorageclass, threadlocal, unnamed_addr, | ||||
3333 | // preemption specifier] (name in VST) | ||||
3334 | // v2: [strtab_offset, strtab_size, v1] | ||||
3335 | StringRef Name; | ||||
3336 | std::tie(Name, Record) = readNameFromStrtab(Record); | ||||
3337 | |||||
3338 | bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; | ||||
3339 | if (Record.size() < (3 + (unsigned)NewRecord)) | ||||
3340 | return error("Invalid record"); | ||||
3341 | unsigned OpNum = 0; | ||||
3342 | Type *FullTy = getFullyStructuredTypeByID(Record[OpNum++]); | ||||
3343 | Type *Ty = flattenPointerTypes(FullTy); | ||||
3344 | if (!Ty) | ||||
3345 | return error("Invalid record"); | ||||
3346 | |||||
3347 | unsigned AddrSpace; | ||||
3348 | if (!NewRecord) { | ||||
3349 | auto *PTy = dyn_cast<PointerType>(Ty); | ||||
3350 | if (!PTy) | ||||
3351 | return error("Invalid type for value"); | ||||
3352 | std::tie(FullTy, Ty) = getPointerElementTypes(FullTy); | ||||
3353 | AddrSpace = PTy->getAddressSpace(); | ||||
3354 | } else { | ||||
3355 | AddrSpace = Record[OpNum++]; | ||||
3356 | } | ||||
3357 | |||||
3358 | auto Val = Record[OpNum++]; | ||||
3359 | auto Linkage = Record[OpNum++]; | ||||
3360 | GlobalIndirectSymbol *NewGA; | ||||
3361 | if (BitCode == bitc::MODULE_CODE_ALIAS || | ||||
3362 | BitCode == bitc::MODULE_CODE_ALIAS_OLD) | ||||
3363 | NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, | ||||
3364 | TheModule); | ||||
3365 | else | ||||
3366 | NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, | ||||
3367 | nullptr, TheModule); | ||||
3368 | |||||
3369 | assert(NewGA->getValueType() == flattenPointerTypes(FullTy) &&((NewGA->getValueType() == flattenPointerTypes(FullTy) && "Incorrect fully structured type provided for GlobalIndirectSymbol" ) ? static_cast<void> (0) : __assert_fail ("NewGA->getValueType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for GlobalIndirectSymbol\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3370, __PRETTY_FUNCTION__)) | ||||
3370 | "Incorrect fully structured type provided for GlobalIndirectSymbol")((NewGA->getValueType() == flattenPointerTypes(FullTy) && "Incorrect fully structured type provided for GlobalIndirectSymbol" ) ? static_cast<void> (0) : __assert_fail ("NewGA->getValueType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for GlobalIndirectSymbol\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3370, __PRETTY_FUNCTION__)); | ||||
3371 | // Old bitcode files didn't have visibility field. | ||||
3372 | // Local linkage must have default visibility. | ||||
3373 | if (OpNum != Record.size()) { | ||||
3374 | auto VisInd = OpNum++; | ||||
3375 | if (!NewGA->hasLocalLinkage()) | ||||
3376 | // FIXME: Change to an error if non-default in 4.0. | ||||
3377 | NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); | ||||
3378 | } | ||||
3379 | if (BitCode == bitc::MODULE_CODE_ALIAS || | ||||
3380 | BitCode == bitc::MODULE_CODE_ALIAS_OLD) { | ||||
3381 | if (OpNum != Record.size()) | ||||
3382 | NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); | ||||
3383 | else | ||||
3384 | upgradeDLLImportExportLinkage(NewGA, Linkage); | ||||
3385 | if (OpNum != Record.size()) | ||||
3386 | NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); | ||||
3387 | if (OpNum != Record.size()) | ||||
3388 | NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); | ||||
3389 | } | ||||
3390 | if (OpNum != Record.size()) | ||||
3391 | NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++])); | ||||
3392 | inferDSOLocal(NewGA); | ||||
3393 | |||||
3394 | // Check whether we have enough values to read a partition name. | ||||
3395 | if (OpNum + 1 < Record.size()) { | ||||
3396 | NewGA->setPartition( | ||||
3397 | StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1])); | ||||
3398 | OpNum += 2; | ||||
3399 | } | ||||
3400 | |||||
3401 | FullTy = PointerType::get(FullTy, AddrSpace); | ||||
3402 | assert(NewGA->getType() == flattenPointerTypes(FullTy) &&((NewGA->getType() == flattenPointerTypes(FullTy) && "Incorrect fully structured type provided for GlobalIndirectSymbol" ) ? static_cast<void> (0) : __assert_fail ("NewGA->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for GlobalIndirectSymbol\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3403, __PRETTY_FUNCTION__)) | ||||
3403 | "Incorrect fully structured type provided for GlobalIndirectSymbol")((NewGA->getType() == flattenPointerTypes(FullTy) && "Incorrect fully structured type provided for GlobalIndirectSymbol" ) ? static_cast<void> (0) : __assert_fail ("NewGA->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for GlobalIndirectSymbol\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3403, __PRETTY_FUNCTION__)); | ||||
3404 | ValueList.push_back(NewGA, FullTy); | ||||
3405 | IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); | ||||
3406 | return Error::success(); | ||||
3407 | } | ||||
3408 | |||||
3409 | Error BitcodeReader::parseModule(uint64_t ResumeBit, | ||||
3410 | bool ShouldLazyLoadMetadata) { | ||||
3411 | if (ResumeBit) { | ||||
3412 | if (Error JumpFailed = Stream.JumpToBit(ResumeBit)) | ||||
3413 | return JumpFailed; | ||||
3414 | } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) | ||||
3415 | return Err; | ||||
3416 | |||||
3417 | SmallVector<uint64_t, 64> Record; | ||||
3418 | |||||
3419 | // Read all the records for this module. | ||||
3420 | while (true) { | ||||
3421 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
3422 | if (!MaybeEntry) | ||||
3423 | return MaybeEntry.takeError(); | ||||
3424 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
3425 | |||||
3426 | switch (Entry.Kind) { | ||||
3427 | case BitstreamEntry::Error: | ||||
3428 | return error("Malformed block"); | ||||
3429 | case BitstreamEntry::EndBlock: | ||||
3430 | return globalCleanup(); | ||||
3431 | |||||
3432 | case BitstreamEntry::SubBlock: | ||||
3433 | switch (Entry.ID) { | ||||
3434 | default: // Skip unknown content. | ||||
3435 | if (Error Err = Stream.SkipBlock()) | ||||
3436 | return Err; | ||||
3437 | break; | ||||
3438 | case bitc::BLOCKINFO_BLOCK_ID: | ||||
3439 | if (readBlockInfo()) | ||||
3440 | return error("Malformed block"); | ||||
3441 | break; | ||||
3442 | case bitc::PARAMATTR_BLOCK_ID: | ||||
3443 | if (Error Err = parseAttributeBlock()) | ||||
3444 | return Err; | ||||
3445 | break; | ||||
3446 | case bitc::PARAMATTR_GROUP_BLOCK_ID: | ||||
3447 | if (Error Err = parseAttributeGroupBlock()) | ||||
3448 | return Err; | ||||
3449 | break; | ||||
3450 | case bitc::TYPE_BLOCK_ID_NEW: | ||||
3451 | if (Error Err = parseTypeTable()) | ||||
3452 | return Err; | ||||
3453 | break; | ||||
3454 | case bitc::VALUE_SYMTAB_BLOCK_ID: | ||||
3455 | if (!SeenValueSymbolTable) { | ||||
3456 | // Either this is an old form VST without function index and an | ||||
3457 | // associated VST forward declaration record (which would have caused | ||||
3458 | // the VST to be jumped to and parsed before it was encountered | ||||
3459 | // normally in the stream), or there were no function blocks to | ||||
3460 | // trigger an earlier parsing of the VST. | ||||
3461 | assert(VSTOffset == 0 || FunctionsWithBodies.empty())((VSTOffset == 0 || FunctionsWithBodies.empty()) ? static_cast <void> (0) : __assert_fail ("VSTOffset == 0 || FunctionsWithBodies.empty()" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3461, __PRETTY_FUNCTION__)); | ||||
3462 | if (Error Err = parseValueSymbolTable()) | ||||
3463 | return Err; | ||||
3464 | SeenValueSymbolTable = true; | ||||
3465 | } else { | ||||
3466 | // We must have had a VST forward declaration record, which caused | ||||
3467 | // the parser to jump to and parse the VST earlier. | ||||
3468 | assert(VSTOffset > 0)((VSTOffset > 0) ? static_cast<void> (0) : __assert_fail ("VSTOffset > 0", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3468, __PRETTY_FUNCTION__)); | ||||
3469 | if (Error Err = Stream.SkipBlock()) | ||||
3470 | return Err; | ||||
3471 | } | ||||
3472 | break; | ||||
3473 | case bitc::CONSTANTS_BLOCK_ID: | ||||
3474 | if (Error Err = parseConstants()) | ||||
3475 | return Err; | ||||
3476 | if (Error Err = resolveGlobalAndIndirectSymbolInits()) | ||||
3477 | return Err; | ||||
3478 | break; | ||||
3479 | case bitc::METADATA_BLOCK_ID: | ||||
3480 | if (ShouldLazyLoadMetadata) { | ||||
3481 | if (Error Err = rememberAndSkipMetadata()) | ||||
3482 | return Err; | ||||
3483 | break; | ||||
3484 | } | ||||
3485 | assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata")((DeferredMetadataInfo.empty() && "Unexpected deferred metadata" ) ? static_cast<void> (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Unexpected deferred metadata\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3485, __PRETTY_FUNCTION__)); | ||||
3486 | if (Error Err = MDLoader->parseModuleMetadata()) | ||||
3487 | return Err; | ||||
3488 | break; | ||||
3489 | case bitc::METADATA_KIND_BLOCK_ID: | ||||
3490 | if (Error Err = MDLoader->parseMetadataKinds()) | ||||
3491 | return Err; | ||||
3492 | break; | ||||
3493 | case bitc::FUNCTION_BLOCK_ID: | ||||
3494 | // If this is the first function body we've seen, reverse the | ||||
3495 | // FunctionsWithBodies list. | ||||
3496 | if (!SeenFirstFunctionBody) { | ||||
3497 | std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); | ||||
3498 | if (Error Err = globalCleanup()) | ||||
3499 | return Err; | ||||
3500 | SeenFirstFunctionBody = true; | ||||
3501 | } | ||||
3502 | |||||
3503 | if (VSTOffset > 0) { | ||||
3504 | // If we have a VST forward declaration record, make sure we | ||||
3505 | // parse the VST now if we haven't already. It is needed to | ||||
3506 | // set up the DeferredFunctionInfo vector for lazy reading. | ||||
3507 | if (!SeenValueSymbolTable) { | ||||
3508 | if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset)) | ||||
3509 | return Err; | ||||
3510 | SeenValueSymbolTable = true; | ||||
3511 | // Fall through so that we record the NextUnreadBit below. | ||||
3512 | // This is necessary in case we have an anonymous function that | ||||
3513 | // is later materialized. Since it will not have a VST entry we | ||||
3514 | // need to fall back to the lazy parse to find its offset. | ||||
3515 | } else { | ||||
3516 | // If we have a VST forward declaration record, but have already | ||||
3517 | // parsed the VST (just above, when the first function body was | ||||
3518 | // encountered here), then we are resuming the parse after | ||||
3519 | // materializing functions. The ResumeBit points to the | ||||
3520 | // start of the last function block recorded in the | ||||
3521 | // DeferredFunctionInfo map. Skip it. | ||||
3522 | if (Error Err = Stream.SkipBlock()) | ||||
3523 | return Err; | ||||
3524 | continue; | ||||
3525 | } | ||||
3526 | } | ||||
3527 | |||||
3528 | // Support older bitcode files that did not have the function | ||||
3529 | // index in the VST, nor a VST forward declaration record, as | ||||
3530 | // well as anonymous functions that do not have VST entries. | ||||
3531 | // Build the DeferredFunctionInfo vector on the fly. | ||||
3532 | if (Error Err = rememberAndSkipFunctionBody()) | ||||
3533 | return Err; | ||||
3534 | |||||
3535 | // Suspend parsing when we reach the function bodies. Subsequent | ||||
3536 | // materialization calls will resume it when necessary. If the bitcode | ||||
3537 | // file is old, the symbol table will be at the end instead and will not | ||||
3538 | // have been seen yet. In this case, just finish the parse now. | ||||
3539 | if (SeenValueSymbolTable) { | ||||
3540 | NextUnreadBit = Stream.GetCurrentBitNo(); | ||||
3541 | // After the VST has been parsed, we need to make sure intrinsic name | ||||
3542 | // are auto-upgraded. | ||||
3543 | return globalCleanup(); | ||||
3544 | } | ||||
3545 | break; | ||||
3546 | case bitc::USELIST_BLOCK_ID: | ||||
3547 | if (Error Err = parseUseLists()) | ||||
3548 | return Err; | ||||
3549 | break; | ||||
3550 | case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: | ||||
3551 | if (Error Err = parseOperandBundleTags()) | ||||
3552 | return Err; | ||||
3553 | break; | ||||
3554 | case bitc::SYNC_SCOPE_NAMES_BLOCK_ID: | ||||
3555 | if (Error Err = parseSyncScopeNames()) | ||||
3556 | return Err; | ||||
3557 | break; | ||||
3558 | } | ||||
3559 | continue; | ||||
3560 | |||||
3561 | case BitstreamEntry::Record: | ||||
3562 | // The interesting case. | ||||
3563 | break; | ||||
3564 | } | ||||
3565 | |||||
3566 | // Read a record. | ||||
3567 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
3568 | if (!MaybeBitCode) | ||||
3569 | return MaybeBitCode.takeError(); | ||||
3570 | switch (unsigned BitCode = MaybeBitCode.get()) { | ||||
3571 | default: break; // Default behavior, ignore unknown content. | ||||
3572 | case bitc::MODULE_CODE_VERSION: { | ||||
3573 | Expected<unsigned> VersionOrErr = parseVersionRecord(Record); | ||||
3574 | if (!VersionOrErr) | ||||
3575 | return VersionOrErr.takeError(); | ||||
3576 | UseRelativeIDs = *VersionOrErr >= 1; | ||||
3577 | break; | ||||
3578 | } | ||||
3579 | case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] | ||||
3580 | std::string S; | ||||
3581 | if (convertToString(Record, 0, S)) | ||||
3582 | return error("Invalid record"); | ||||
3583 | TheModule->setTargetTriple(S); | ||||
3584 | break; | ||||
3585 | } | ||||
3586 | case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] | ||||
3587 | std::string S; | ||||
3588 | if (convertToString(Record, 0, S)) | ||||
3589 | return error("Invalid record"); | ||||
3590 | TheModule->setDataLayout(S); | ||||
3591 | break; | ||||
3592 | } | ||||
3593 | case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] | ||||
3594 | std::string S; | ||||
3595 | if (convertToString(Record, 0, S)) | ||||
3596 | return error("Invalid record"); | ||||
3597 | TheModule->setModuleInlineAsm(S); | ||||
3598 | break; | ||||
3599 | } | ||||
3600 | case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] | ||||
3601 | // FIXME: Remove in 4.0. | ||||
3602 | std::string S; | ||||
3603 | if (convertToString(Record, 0, S)) | ||||
3604 | return error("Invalid record"); | ||||
3605 | // Ignore value. | ||||
3606 | break; | ||||
3607 | } | ||||
3608 | case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] | ||||
3609 | std::string S; | ||||
3610 | if (convertToString(Record, 0, S)) | ||||
3611 | return error("Invalid record"); | ||||
3612 | SectionTable.push_back(S); | ||||
3613 | break; | ||||
3614 | } | ||||
3615 | case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] | ||||
3616 | std::string S; | ||||
3617 | if (convertToString(Record, 0, S)) | ||||
3618 | return error("Invalid record"); | ||||
3619 | GCTable.push_back(S); | ||||
3620 | break; | ||||
3621 | } | ||||
3622 | case bitc::MODULE_CODE_COMDAT: | ||||
3623 | if (Error Err = parseComdatRecord(Record)) | ||||
3624 | return Err; | ||||
3625 | break; | ||||
3626 | case bitc::MODULE_CODE_GLOBALVAR: | ||||
3627 | if (Error Err = parseGlobalVarRecord(Record)) | ||||
3628 | return Err; | ||||
3629 | break; | ||||
3630 | case bitc::MODULE_CODE_FUNCTION: | ||||
3631 | if (Error Err = parseFunctionRecord(Record)) | ||||
3632 | return Err; | ||||
3633 | break; | ||||
3634 | case bitc::MODULE_CODE_IFUNC: | ||||
3635 | case bitc::MODULE_CODE_ALIAS: | ||||
3636 | case bitc::MODULE_CODE_ALIAS_OLD: | ||||
3637 | if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record)) | ||||
3638 | return Err; | ||||
3639 | break; | ||||
3640 | /// MODULE_CODE_VSTOFFSET: [offset] | ||||
3641 | case bitc::MODULE_CODE_VSTOFFSET: | ||||
3642 | if (Record.size() < 1) | ||||
3643 | return error("Invalid record"); | ||||
3644 | // Note that we subtract 1 here because the offset is relative to one word | ||||
3645 | // before the start of the identification or module block, which was | ||||
3646 | // historically always the start of the regular bitcode header. | ||||
3647 | VSTOffset = Record[0] - 1; | ||||
3648 | break; | ||||
3649 | /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] | ||||
3650 | case bitc::MODULE_CODE_SOURCE_FILENAME: | ||||
3651 | SmallString<128> ValueName; | ||||
3652 | if (convertToString(Record, 0, ValueName)) | ||||
3653 | return error("Invalid record"); | ||||
3654 | TheModule->setSourceFileName(ValueName); | ||||
3655 | break; | ||||
3656 | } | ||||
3657 | Record.clear(); | ||||
3658 | |||||
3659 | // Upgrade data layout string. | ||||
3660 | std::string DL = llvm::UpgradeDataLayoutString( | ||||
3661 | TheModule->getDataLayoutStr(), TheModule->getTargetTriple()); | ||||
3662 | TheModule->setDataLayout(DL); | ||||
3663 | } | ||||
3664 | } | ||||
3665 | |||||
3666 | Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, | ||||
3667 | bool IsImporting) { | ||||
3668 | TheModule = M; | ||||
3669 | MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, | ||||
3670 | [&](unsigned ID) { return getTypeByID(ID); }); | ||||
3671 | return parseModule(0, ShouldLazyLoadMetadata); | ||||
3672 | } | ||||
3673 | |||||
3674 | Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { | ||||
3675 | if (!isa<PointerType>(PtrType)) | ||||
3676 | return error("Load/Store operand is not a pointer type"); | ||||
3677 | Type *ElemType = cast<PointerType>(PtrType)->getElementType(); | ||||
3678 | |||||
3679 | if (ValType && ValType != ElemType) | ||||
3680 | return error("Explicit load/store type does not match pointee " | ||||
3681 | "type of pointer operand"); | ||||
3682 | if (!PointerType::isLoadableOrStorableType(ElemType)) | ||||
3683 | return error("Cannot load/store from pointer"); | ||||
3684 | return Error::success(); | ||||
3685 | } | ||||
3686 | |||||
3687 | void BitcodeReader::propagateByValTypes(CallBase *CB, | ||||
3688 | ArrayRef<Type *> ArgsFullTys) { | ||||
3689 | for (unsigned i = 0; i != CB->arg_size(); ++i) { | ||||
3690 | if (!CB->paramHasAttr(i, Attribute::ByVal)) | ||||
3691 | continue; | ||||
3692 | |||||
3693 | CB->removeParamAttr(i, Attribute::ByVal); | ||||
3694 | CB->addParamAttr( | ||||
3695 | i, Attribute::getWithByValType( | ||||
3696 | Context, getPointerElementFlatType(ArgsFullTys[i]))); | ||||
3697 | } | ||||
3698 | } | ||||
3699 | |||||
3700 | /// Lazily parse the specified function body block. | ||||
3701 | Error BitcodeReader::parseFunctionBody(Function *F) { | ||||
3702 | if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) | ||||
3703 | return Err; | ||||
3704 | |||||
3705 | // Unexpected unresolved metadata when parsing function. | ||||
3706 | if (MDLoader->hasFwdRefs()) | ||||
3707 | return error("Invalid function metadata: incoming forward references"); | ||||
3708 | |||||
3709 | InstructionList.clear(); | ||||
3710 | unsigned ModuleValueListSize = ValueList.size(); | ||||
3711 | unsigned ModuleMDLoaderSize = MDLoader->size(); | ||||
3712 | |||||
3713 | // Add all the function arguments to the value table. | ||||
3714 | unsigned ArgNo = 0; | ||||
3715 | FunctionType *FullFTy = FunctionTypes[F]; | ||||
3716 | for (Argument &I : F->args()) { | ||||
3717 | assert(I.getType() == flattenPointerTypes(FullFTy->getParamType(ArgNo)) &&((I.getType() == flattenPointerTypes(FullFTy->getParamType (ArgNo)) && "Incorrect fully specified type for Function Argument" ) ? static_cast<void> (0) : __assert_fail ("I.getType() == flattenPointerTypes(FullFTy->getParamType(ArgNo)) && \"Incorrect fully specified type for Function Argument\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3718, __PRETTY_FUNCTION__)) | ||||
3718 | "Incorrect fully specified type for Function Argument")((I.getType() == flattenPointerTypes(FullFTy->getParamType (ArgNo)) && "Incorrect fully specified type for Function Argument" ) ? static_cast<void> (0) : __assert_fail ("I.getType() == flattenPointerTypes(FullFTy->getParamType(ArgNo)) && \"Incorrect fully specified type for Function Argument\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3718, __PRETTY_FUNCTION__)); | ||||
3719 | ValueList.push_back(&I, FullFTy->getParamType(ArgNo++)); | ||||
3720 | } | ||||
3721 | unsigned NextValueNo = ValueList.size(); | ||||
3722 | BasicBlock *CurBB = nullptr; | ||||
3723 | unsigned CurBBNo = 0; | ||||
3724 | |||||
3725 | DebugLoc LastLoc; | ||||
3726 | auto getLastInstruction = [&]() -> Instruction * { | ||||
3727 | if (CurBB && !CurBB->empty()) | ||||
3728 | return &CurBB->back(); | ||||
3729 | else if (CurBBNo && FunctionBBs[CurBBNo - 1] && | ||||
3730 | !FunctionBBs[CurBBNo - 1]->empty()) | ||||
3731 | return &FunctionBBs[CurBBNo - 1]->back(); | ||||
3732 | return nullptr; | ||||
3733 | }; | ||||
3734 | |||||
3735 | std::vector<OperandBundleDef> OperandBundles; | ||||
3736 | |||||
3737 | // Read all the records. | ||||
3738 | SmallVector<uint64_t, 64> Record; | ||||
3739 | |||||
3740 | while (true) { | ||||
3741 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
3742 | if (!MaybeEntry) | ||||
3743 | return MaybeEntry.takeError(); | ||||
3744 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
3745 | |||||
3746 | switch (Entry.Kind) { | ||||
3747 | case BitstreamEntry::Error: | ||||
3748 | return error("Malformed block"); | ||||
3749 | case BitstreamEntry::EndBlock: | ||||
3750 | goto OutOfRecordLoop; | ||||
3751 | |||||
3752 | case BitstreamEntry::SubBlock: | ||||
3753 | switch (Entry.ID) { | ||||
3754 | default: // Skip unknown content. | ||||
3755 | if (Error Err = Stream.SkipBlock()) | ||||
3756 | return Err; | ||||
3757 | break; | ||||
3758 | case bitc::CONSTANTS_BLOCK_ID: | ||||
3759 | if (Error Err = parseConstants()) | ||||
3760 | return Err; | ||||
3761 | NextValueNo = ValueList.size(); | ||||
3762 | break; | ||||
3763 | case bitc::VALUE_SYMTAB_BLOCK_ID: | ||||
3764 | if (Error Err = parseValueSymbolTable()) | ||||
3765 | return Err; | ||||
3766 | break; | ||||
3767 | case bitc::METADATA_ATTACHMENT_ID: | ||||
3768 | if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList)) | ||||
3769 | return Err; | ||||
3770 | break; | ||||
3771 | case bitc::METADATA_BLOCK_ID: | ||||
3772 | assert(DeferredMetadataInfo.empty() &&((DeferredMetadataInfo.empty() && "Must read all module-level metadata before function-level" ) ? static_cast<void> (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Must read all module-level metadata before function-level\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3773, __PRETTY_FUNCTION__)) | ||||
3773 | "Must read all module-level metadata before function-level")((DeferredMetadataInfo.empty() && "Must read all module-level metadata before function-level" ) ? static_cast<void> (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Must read all module-level metadata before function-level\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3773, __PRETTY_FUNCTION__)); | ||||
3774 | if (Error Err = MDLoader->parseFunctionMetadata()) | ||||
3775 | return Err; | ||||
3776 | break; | ||||
3777 | case bitc::USELIST_BLOCK_ID: | ||||
3778 | if (Error Err = parseUseLists()) | ||||
3779 | return Err; | ||||
3780 | break; | ||||
3781 | } | ||||
3782 | continue; | ||||
3783 | |||||
3784 | case BitstreamEntry::Record: | ||||
3785 | // The interesting case. | ||||
3786 | break; | ||||
3787 | } | ||||
3788 | |||||
3789 | // Read a record. | ||||
3790 | Record.clear(); | ||||
3791 | Instruction *I = nullptr; | ||||
3792 | Type *FullTy = nullptr; | ||||
3793 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
3794 | if (!MaybeBitCode) | ||||
3795 | return MaybeBitCode.takeError(); | ||||
3796 | switch (unsigned BitCode = MaybeBitCode.get()) { | ||||
3797 | default: // Default behavior: reject | ||||
3798 | return error("Invalid value"); | ||||
3799 | case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] | ||||
3800 | if (Record.size() < 1 || Record[0] == 0) | ||||
3801 | return error("Invalid record"); | ||||
3802 | // Create all the basic blocks for the function. | ||||
3803 | FunctionBBs.resize(Record[0]); | ||||
3804 | |||||
3805 | // See if anything took the address of blocks in this function. | ||||
3806 | auto BBFRI = BasicBlockFwdRefs.find(F); | ||||
3807 | if (BBFRI == BasicBlockFwdRefs.end()) { | ||||
3808 | for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) | ||||
3809 | FunctionBBs[i] = BasicBlock::Create(Context, "", F); | ||||
3810 | } else { | ||||
3811 | auto &BBRefs = BBFRI->second; | ||||
3812 | // Check for invalid basic block references. | ||||
3813 | if (BBRefs.size() > FunctionBBs.size()) | ||||
3814 | return error("Invalid ID"); | ||||
3815 | assert(!BBRefs.empty() && "Unexpected empty array")((!BBRefs.empty() && "Unexpected empty array") ? static_cast <void> (0) : __assert_fail ("!BBRefs.empty() && \"Unexpected empty array\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3815, __PRETTY_FUNCTION__)); | ||||
3816 | assert(!BBRefs.front() && "Invalid reference to entry block")((!BBRefs.front() && "Invalid reference to entry block" ) ? static_cast<void> (0) : __assert_fail ("!BBRefs.front() && \"Invalid reference to entry block\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3816, __PRETTY_FUNCTION__)); | ||||
3817 | for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; | ||||
3818 | ++I) | ||||
3819 | if (I < RE && BBRefs[I]) { | ||||
3820 | BBRefs[I]->insertInto(F); | ||||
3821 | FunctionBBs[I] = BBRefs[I]; | ||||
3822 | } else { | ||||
3823 | FunctionBBs[I] = BasicBlock::Create(Context, "", F); | ||||
3824 | } | ||||
3825 | |||||
3826 | // Erase from the table. | ||||
3827 | BasicBlockFwdRefs.erase(BBFRI); | ||||
3828 | } | ||||
3829 | |||||
3830 | CurBB = FunctionBBs[0]; | ||||
3831 | continue; | ||||
3832 | } | ||||
3833 | |||||
3834 | case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN | ||||
3835 | // This record indicates that the last instruction is at the same | ||||
3836 | // location as the previous instruction with a location. | ||||
3837 | I = getLastInstruction(); | ||||
3838 | |||||
3839 | if (!I) | ||||
3840 | return error("Invalid record"); | ||||
3841 | I->setDebugLoc(LastLoc); | ||||
3842 | I = nullptr; | ||||
3843 | continue; | ||||
3844 | |||||
3845 | case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] | ||||
3846 | I = getLastInstruction(); | ||||
3847 | if (!I || Record.size() < 4) | ||||
3848 | return error("Invalid record"); | ||||
3849 | |||||
3850 | unsigned Line = Record[0], Col = Record[1]; | ||||
3851 | unsigned ScopeID = Record[2], IAID = Record[3]; | ||||
3852 | bool isImplicitCode = Record.size() == 5 && Record[4]; | ||||
3853 | |||||
3854 | MDNode *Scope = nullptr, *IA = nullptr; | ||||
3855 | if (ScopeID) { | ||||
3856 | Scope = dyn_cast_or_null<MDNode>( | ||||
3857 | MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1)); | ||||
3858 | if (!Scope) | ||||
3859 | return error("Invalid record"); | ||||
3860 | } | ||||
3861 | if (IAID) { | ||||
3862 | IA = dyn_cast_or_null<MDNode>( | ||||
3863 | MDLoader->getMetadataFwdRefOrLoad(IAID - 1)); | ||||
3864 | if (!IA) | ||||
3865 | return error("Invalid record"); | ||||
3866 | } | ||||
3867 | LastLoc = DebugLoc::get(Line, Col, Scope, IA, isImplicitCode); | ||||
3868 | I->setDebugLoc(LastLoc); | ||||
3869 | I = nullptr; | ||||
3870 | continue; | ||||
3871 | } | ||||
3872 | case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode] | ||||
3873 | unsigned OpNum = 0; | ||||
3874 | Value *LHS; | ||||
3875 | if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || | ||||
3876 | OpNum+1 > Record.size()) | ||||
3877 | return error("Invalid record"); | ||||
3878 | |||||
3879 | int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType()); | ||||
3880 | if (Opc == -1) | ||||
3881 | return error("Invalid record"); | ||||
3882 | I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); | ||||
3883 | InstructionList.push_back(I); | ||||
3884 | if (OpNum < Record.size()) { | ||||
3885 | if (isa<FPMathOperator>(I)) { | ||||
3886 | FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); | ||||
3887 | if (FMF.any()) | ||||
3888 | I->setFastMathFlags(FMF); | ||||
3889 | } | ||||
3890 | } | ||||
3891 | break; | ||||
3892 | } | ||||
3893 | case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] | ||||
3894 | unsigned OpNum = 0; | ||||
3895 | Value *LHS, *RHS; | ||||
3896 | if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || | ||||
3897 | popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || | ||||
3898 | OpNum+1 > Record.size()) | ||||
3899 | return error("Invalid record"); | ||||
3900 | |||||
3901 | int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); | ||||
3902 | if (Opc == -1) | ||||
3903 | return error("Invalid record"); | ||||
3904 | I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); | ||||
3905 | InstructionList.push_back(I); | ||||
3906 | if (OpNum < Record.size()) { | ||||
3907 | if (Opc == Instruction::Add || | ||||
3908 | Opc == Instruction::Sub || | ||||
3909 | Opc == Instruction::Mul || | ||||
3910 | Opc == Instruction::Shl) { | ||||
3911 | if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) | ||||
3912 | cast<BinaryOperator>(I)->setHasNoSignedWrap(true); | ||||
3913 | if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) | ||||
3914 | cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); | ||||
3915 | } else if (Opc == Instruction::SDiv || | ||||
3916 | Opc == Instruction::UDiv || | ||||
3917 | Opc == Instruction::LShr || | ||||
3918 | Opc == Instruction::AShr) { | ||||
3919 | if (Record[OpNum] & (1 << bitc::PEO_EXACT)) | ||||
3920 | cast<BinaryOperator>(I)->setIsExact(true); | ||||
3921 | } else if (isa<FPMathOperator>(I)) { | ||||
3922 | FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); | ||||
3923 | if (FMF.any()) | ||||
3924 | I->setFastMathFlags(FMF); | ||||
3925 | } | ||||
3926 | |||||
3927 | } | ||||
3928 | break; | ||||
3929 | } | ||||
3930 | case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] | ||||
3931 | unsigned OpNum = 0; | ||||
3932 | Value *Op; | ||||
3933 | if (getValueTypePair(Record, OpNum, NextValueNo, Op) || | ||||
3934 | OpNum+2 != Record.size()) | ||||
3935 | return error("Invalid record"); | ||||
3936 | |||||
3937 | FullTy = getFullyStructuredTypeByID(Record[OpNum]); | ||||
3938 | Type *ResTy = flattenPointerTypes(FullTy); | ||||
3939 | int Opc = getDecodedCastOpcode(Record[OpNum + 1]); | ||||
3940 | if (Opc == -1 || !ResTy) | ||||
3941 | return error("Invalid record"); | ||||
3942 | Instruction *Temp = nullptr; | ||||
3943 | if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { | ||||
3944 | if (Temp) { | ||||
3945 | InstructionList.push_back(Temp); | ||||
3946 | assert(CurBB && "No current BB?")((CurBB && "No current BB?") ? static_cast<void> (0) : __assert_fail ("CurBB && \"No current BB?\"", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3946, __PRETTY_FUNCTION__)); | ||||
3947 | CurBB->getInstList().push_back(Temp); | ||||
3948 | } | ||||
3949 | } else { | ||||
3950 | auto CastOp = (Instruction::CastOps)Opc; | ||||
3951 | if (!CastInst::castIsValid(CastOp, Op, ResTy)) | ||||
3952 | return error("Invalid cast"); | ||||
3953 | I = CastInst::Create(CastOp, Op, ResTy); | ||||
3954 | } | ||||
3955 | InstructionList.push_back(I); | ||||
3956 | break; | ||||
3957 | } | ||||
3958 | case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: | ||||
3959 | case bitc::FUNC_CODE_INST_GEP_OLD: | ||||
3960 | case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] | ||||
3961 | unsigned OpNum = 0; | ||||
3962 | |||||
3963 | Type *Ty; | ||||
3964 | bool InBounds; | ||||
3965 | |||||
3966 | if (BitCode == bitc::FUNC_CODE_INST_GEP) { | ||||
3967 | InBounds = Record[OpNum++]; | ||||
3968 | FullTy = getFullyStructuredTypeByID(Record[OpNum++]); | ||||
3969 | Ty = flattenPointerTypes(FullTy); | ||||
3970 | } else { | ||||
3971 | InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; | ||||
3972 | Ty = nullptr; | ||||
3973 | } | ||||
3974 | |||||
3975 | Value *BasePtr; | ||||
3976 | Type *FullBaseTy = nullptr; | ||||
3977 | if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, &FullBaseTy)) | ||||
3978 | return error("Invalid record"); | ||||
3979 | |||||
3980 | if (!Ty) { | ||||
3981 | std::tie(FullTy, Ty) = | ||||
3982 | getPointerElementTypes(FullBaseTy->getScalarType()); | ||||
3983 | } else if (Ty != getPointerElementFlatType(FullBaseTy->getScalarType())) | ||||
3984 | return error( | ||||
3985 | "Explicit gep type does not match pointee type of pointer operand"); | ||||
3986 | |||||
3987 | SmallVector<Value*, 16> GEPIdx; | ||||
3988 | while (OpNum != Record.size()) { | ||||
3989 | Value *Op; | ||||
3990 | if (getValueTypePair(Record, OpNum, NextValueNo, Op)) | ||||
3991 | return error("Invalid record"); | ||||
3992 | GEPIdx.push_back(Op); | ||||
3993 | } | ||||
3994 | |||||
3995 | I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); | ||||
3996 | FullTy = GetElementPtrInst::getGEPReturnType(FullTy, I, GEPIdx); | ||||
3997 | |||||
3998 | InstructionList.push_back(I); | ||||
3999 | if (InBounds) | ||||
4000 | cast<GetElementPtrInst>(I)->setIsInBounds(true); | ||||
4001 | break; | ||||
4002 | } | ||||
4003 | |||||
4004 | case bitc::FUNC_CODE_INST_EXTRACTVAL: { | ||||
4005 | // EXTRACTVAL: [opty, opval, n x indices] | ||||
4006 | unsigned OpNum = 0; | ||||
4007 | Value *Agg; | ||||
4008 | if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy)) | ||||
4009 | return error("Invalid record"); | ||||
4010 | |||||
4011 | unsigned RecSize = Record.size(); | ||||
4012 | if (OpNum == RecSize) | ||||
4013 | return error("EXTRACTVAL: Invalid instruction with 0 indices"); | ||||
4014 | |||||
4015 | SmallVector<unsigned, 4> EXTRACTVALIdx; | ||||
4016 | for (; OpNum != RecSize; ++OpNum) { | ||||
4017 | bool IsArray = FullTy->isArrayTy(); | ||||
4018 | bool IsStruct = FullTy->isStructTy(); | ||||
4019 | uint64_t Index = Record[OpNum]; | ||||
4020 | |||||
4021 | if (!IsStruct && !IsArray) | ||||
4022 | return error("EXTRACTVAL: Invalid type"); | ||||
4023 | if ((unsigned)Index != Index) | ||||
4024 | return error("Invalid value"); | ||||
4025 | if (IsStruct && Index >= FullTy->getStructNumElements()) | ||||
4026 | return error("EXTRACTVAL: Invalid struct index"); | ||||
4027 | if (IsArray && Index >= FullTy->getArrayNumElements()) | ||||
4028 | return error("EXTRACTVAL: Invalid array index"); | ||||
4029 | EXTRACTVALIdx.push_back((unsigned)Index); | ||||
4030 | |||||
4031 | if (IsStruct) | ||||
4032 | FullTy = FullTy->getStructElementType(Index); | ||||
4033 | else | ||||
4034 | FullTy = FullTy->getArrayElementType(); | ||||
4035 | } | ||||
4036 | |||||
4037 | I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); | ||||
4038 | InstructionList.push_back(I); | ||||
4039 | break; | ||||
4040 | } | ||||
4041 | |||||
4042 | case bitc::FUNC_CODE_INST_INSERTVAL: { | ||||
4043 | // INSERTVAL: [opty, opval, opty, opval, n x indices] | ||||
4044 | unsigned OpNum = 0; | ||||
4045 | Value *Agg; | ||||
4046 | if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy)) | ||||
4047 | return error("Invalid record"); | ||||
4048 | Value *Val; | ||||
4049 | if (getValueTypePair(Record, OpNum, NextValueNo, Val)) | ||||
4050 | return error("Invalid record"); | ||||
4051 | |||||
4052 | unsigned RecSize = Record.size(); | ||||
4053 | if (OpNum == RecSize) | ||||
4054 | return error("INSERTVAL: Invalid instruction with 0 indices"); | ||||
4055 | |||||
4056 | SmallVector<unsigned, 4> INSERTVALIdx; | ||||
4057 | Type *CurTy = Agg->getType(); | ||||
4058 | for (; OpNum != RecSize; ++OpNum) { | ||||
4059 | bool IsArray = CurTy->isArrayTy(); | ||||
4060 | bool IsStruct = CurTy->isStructTy(); | ||||
4061 | uint64_t Index = Record[OpNum]; | ||||
4062 | |||||
4063 | if (!IsStruct && !IsArray) | ||||
4064 | return error("INSERTVAL: Invalid type"); | ||||
4065 | if ((unsigned)Index != Index) | ||||
4066 | return error("Invalid value"); | ||||
4067 | if (IsStruct && Index >= CurTy->getStructNumElements()) | ||||
4068 | return error("INSERTVAL: Invalid struct index"); | ||||
4069 | if (IsArray && Index >= CurTy->getArrayNumElements()) | ||||
4070 | return error("INSERTVAL: Invalid array index"); | ||||
4071 | |||||
4072 | INSERTVALIdx.push_back((unsigned)Index); | ||||
4073 | if (IsStruct) | ||||
4074 | CurTy = CurTy->getStructElementType(Index); | ||||
4075 | else | ||||
4076 | CurTy = CurTy->getArrayElementType(); | ||||
4077 | } | ||||
4078 | |||||
4079 | if (CurTy != Val->getType()) | ||||
4080 | return error("Inserted value type doesn't match aggregate type"); | ||||
4081 | |||||
4082 | I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); | ||||
4083 | InstructionList.push_back(I); | ||||
4084 | break; | ||||
4085 | } | ||||
4086 | |||||
4087 | case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] | ||||
4088 | // obsolete form of select | ||||
4089 | // handles select i1 ... in old bitcode | ||||
4090 | unsigned OpNum = 0; | ||||
4091 | Value *TrueVal, *FalseVal, *Cond; | ||||
4092 | if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) || | ||||
4093 | popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || | ||||
4094 | popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) | ||||
4095 | return error("Invalid record"); | ||||
4096 | |||||
4097 | I = SelectInst::Create(Cond, TrueVal, FalseVal); | ||||
4098 | InstructionList.push_back(I); | ||||
4099 | break; | ||||
4100 | } | ||||
4101 | |||||
4102 | case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] | ||||
4103 | // new form of select | ||||
4104 | // handles select i1 or select [N x i1] | ||||
4105 | unsigned OpNum = 0; | ||||
4106 | Value *TrueVal, *FalseVal, *Cond; | ||||
4107 | if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) || | ||||
4108 | popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || | ||||
4109 | getValueTypePair(Record, OpNum, NextValueNo, Cond)) | ||||
4110 | return error("Invalid record"); | ||||
4111 | |||||
4112 | // select condition can be either i1 or [N x i1] | ||||
4113 | if (VectorType* vector_type = | ||||
4114 | dyn_cast<VectorType>(Cond->getType())) { | ||||
4115 | // expect <n x i1> | ||||
4116 | if (vector_type->getElementType() != Type::getInt1Ty(Context)) | ||||
4117 | return error("Invalid type for value"); | ||||
4118 | } else { | ||||
4119 | // expect i1 | ||||
4120 | if (Cond->getType() != Type::getInt1Ty(Context)) | ||||
4121 | return error("Invalid type for value"); | ||||
4122 | } | ||||
4123 | |||||
4124 | I = SelectInst::Create(Cond, TrueVal, FalseVal); | ||||
4125 | InstructionList.push_back(I); | ||||
4126 | if (OpNum < Record.size() && isa<FPMathOperator>(I)) { | ||||
4127 | FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); | ||||
4128 | if (FMF.any()) | ||||
4129 | I->setFastMathFlags(FMF); | ||||
4130 | } | ||||
4131 | break; | ||||
4132 | } | ||||
4133 | |||||
4134 | case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] | ||||
4135 | unsigned OpNum = 0; | ||||
4136 | Value *Vec, *Idx; | ||||
4137 | if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy) || | ||||
4138 | getValueTypePair(Record, OpNum, NextValueNo, Idx)) | ||||
4139 | return error("Invalid record"); | ||||
4140 | if (!Vec->getType()->isVectorTy()) | ||||
4141 | return error("Invalid type for value"); | ||||
4142 | I = ExtractElementInst::Create(Vec, Idx); | ||||
4143 | FullTy = FullTy->getVectorElementType(); | ||||
4144 | InstructionList.push_back(I); | ||||
4145 | break; | ||||
4146 | } | ||||
4147 | |||||
4148 | case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] | ||||
4149 | unsigned OpNum = 0; | ||||
4150 | Value *Vec, *Elt, *Idx; | ||||
4151 | if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy)) | ||||
4152 | return error("Invalid record"); | ||||
4153 | if (!Vec->getType()->isVectorTy()) | ||||
4154 | return error("Invalid type for value"); | ||||
4155 | if (popValue(Record, OpNum, NextValueNo, | ||||
4156 | cast<VectorType>(Vec->getType())->getElementType(), Elt) || | ||||
4157 | getValueTypePair(Record, OpNum, NextValueNo, Idx)) | ||||
4158 | return error("Invalid record"); | ||||
4159 | I = InsertElementInst::Create(Vec, Elt, Idx); | ||||
4160 | InstructionList.push_back(I); | ||||
4161 | break; | ||||
4162 | } | ||||
4163 | |||||
4164 | case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] | ||||
4165 | unsigned OpNum = 0; | ||||
4166 | Value *Vec1, *Vec2, *Mask; | ||||
4167 | if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, &FullTy) || | ||||
4168 | popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) | ||||
4169 | return error("Invalid record"); | ||||
4170 | |||||
4171 | if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) | ||||
4172 | return error("Invalid record"); | ||||
4173 | if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) | ||||
4174 | return error("Invalid type for value"); | ||||
4175 | |||||
4176 | I = new ShuffleVectorInst(Vec1, Vec2, Mask); | ||||
4177 | FullTy = VectorType::get(FullTy->getVectorElementType(), | ||||
4178 | Mask->getType()->getVectorElementCount()); | ||||
4179 | InstructionList.push_back(I); | ||||
4180 | break; | ||||
4181 | } | ||||
4182 | |||||
4183 | case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] | ||||
4184 | // Old form of ICmp/FCmp returning bool | ||||
4185 | // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were | ||||
4186 | // both legal on vectors but had different behaviour. | ||||
4187 | case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] | ||||
4188 | // FCmp/ICmp returning bool or vector of bool | ||||
4189 | |||||
4190 | unsigned OpNum = 0; | ||||
4191 | Value *LHS, *RHS; | ||||
4192 | if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || | ||||
4193 | popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) | ||||
4194 | return error("Invalid record"); | ||||
4195 | |||||
4196 | if (OpNum >= Record.size()) | ||||
4197 | return error( | ||||
4198 | "Invalid record: operand number exceeded available operands"); | ||||
4199 | |||||
4200 | unsigned PredVal = Record[OpNum]; | ||||
4201 | bool IsFP = LHS->getType()->isFPOrFPVectorTy(); | ||||
4202 | FastMathFlags FMF; | ||||
4203 | if (IsFP && Record.size() > OpNum+1) | ||||
4204 | FMF = getDecodedFastMathFlags(Record[++OpNum]); | ||||
4205 | |||||
4206 | if (OpNum+1 != Record.size()) | ||||
4207 | return error("Invalid record"); | ||||
4208 | |||||
4209 | if (LHS->getType()->isFPOrFPVectorTy()) | ||||
4210 | I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); | ||||
4211 | else | ||||
4212 | I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); | ||||
4213 | |||||
4214 | if (FMF.any()) | ||||
4215 | I->setFastMathFlags(FMF); | ||||
4216 | InstructionList.push_back(I); | ||||
4217 | break; | ||||
4218 | } | ||||
4219 | |||||
4220 | case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] | ||||
4221 | { | ||||
4222 | unsigned Size = Record.size(); | ||||
4223 | if (Size == 0) { | ||||
4224 | I = ReturnInst::Create(Context); | ||||
4225 | InstructionList.push_back(I); | ||||
4226 | break; | ||||
4227 | } | ||||
4228 | |||||
4229 | unsigned OpNum = 0; | ||||
4230 | Value *Op = nullptr; | ||||
4231 | if (getValueTypePair(Record, OpNum, NextValueNo, Op)) | ||||
4232 | return error("Invalid record"); | ||||
4233 | if (OpNum != Record.size()) | ||||
4234 | return error("Invalid record"); | ||||
4235 | |||||
4236 | I = ReturnInst::Create(Context, Op); | ||||
4237 | InstructionList.push_back(I); | ||||
4238 | break; | ||||
4239 | } | ||||
4240 | case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] | ||||
4241 | if (Record.size() != 1 && Record.size() != 3) | ||||
4242 | return error("Invalid record"); | ||||
4243 | BasicBlock *TrueDest = getBasicBlock(Record[0]); | ||||
4244 | if (!TrueDest) | ||||
4245 | return error("Invalid record"); | ||||
4246 | |||||
4247 | if (Record.size() == 1) { | ||||
4248 | I = BranchInst::Create(TrueDest); | ||||
4249 | InstructionList.push_back(I); | ||||
4250 | } | ||||
4251 | else { | ||||
4252 | BasicBlock *FalseDest = getBasicBlock(Record[1]); | ||||
4253 | Value *Cond = getValue(Record, 2, NextValueNo, | ||||
4254 | Type::getInt1Ty(Context)); | ||||
4255 | if (!FalseDest || !Cond) | ||||
4256 | return error("Invalid record"); | ||||
4257 | I = BranchInst::Create(TrueDest, FalseDest, Cond); | ||||
4258 | InstructionList.push_back(I); | ||||
4259 | } | ||||
4260 | break; | ||||
4261 | } | ||||
4262 | case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] | ||||
4263 | if (Record.size() != 1 && Record.size() != 2) | ||||
4264 | return error("Invalid record"); | ||||
4265 | unsigned Idx = 0; | ||||
4266 | Value *CleanupPad = | ||||
4267 | getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); | ||||
4268 | if (!CleanupPad) | ||||
4269 | return error("Invalid record"); | ||||
4270 | BasicBlock *UnwindDest = nullptr; | ||||
4271 | if (Record.size() == 2) { | ||||
4272 | UnwindDest = getBasicBlock(Record[Idx++]); | ||||
4273 | if (!UnwindDest) | ||||
4274 | return error("Invalid record"); | ||||
4275 | } | ||||
4276 | |||||
4277 | I = CleanupReturnInst::Create(CleanupPad, UnwindDest); | ||||
4278 | InstructionList.push_back(I); | ||||
4279 | break; | ||||
4280 | } | ||||
4281 | case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] | ||||
4282 | if (Record.size() != 2) | ||||
4283 | return error("Invalid record"); | ||||
4284 | unsigned Idx = 0; | ||||
4285 | Value *CatchPad = | ||||
4286 | getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); | ||||
4287 | if (!CatchPad) | ||||
4288 | return error("Invalid record"); | ||||
4289 | BasicBlock *BB = getBasicBlock(Record[Idx++]); | ||||
4290 | if (!BB) | ||||
4291 | return error("Invalid record"); | ||||
4292 | |||||
4293 | I = CatchReturnInst::Create(CatchPad, BB); | ||||
4294 | InstructionList.push_back(I); | ||||
4295 | break; | ||||
4296 | } | ||||
4297 | case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] | ||||
4298 | // We must have, at minimum, the outer scope and the number of arguments. | ||||
4299 | if (Record.size() < 2) | ||||
4300 | return error("Invalid record"); | ||||
4301 | |||||
4302 | unsigned Idx = 0; | ||||
4303 | |||||
4304 | Value *ParentPad = | ||||
4305 | getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); | ||||
4306 | |||||
4307 | unsigned NumHandlers = Record[Idx++]; | ||||
4308 | |||||
4309 | SmallVector<BasicBlock *, 2> Handlers; | ||||
4310 | for (unsigned Op = 0; Op != NumHandlers; ++Op) { | ||||
4311 | BasicBlock *BB = getBasicBlock(Record[Idx++]); | ||||
4312 | if (!BB) | ||||
4313 | return error("Invalid record"); | ||||
4314 | Handlers.push_back(BB); | ||||
4315 | } | ||||
4316 | |||||
4317 | BasicBlock *UnwindDest = nullptr; | ||||
4318 | if (Idx + 1 == Record.size()) { | ||||
4319 | UnwindDest = getBasicBlock(Record[Idx++]); | ||||
4320 | if (!UnwindDest) | ||||
4321 | return error("Invalid record"); | ||||
4322 | } | ||||
4323 | |||||
4324 | if (Record.size() != Idx) | ||||
4325 | return error("Invalid record"); | ||||
4326 | |||||
4327 | auto *CatchSwitch = | ||||
4328 | CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); | ||||
4329 | for (BasicBlock *Handler : Handlers) | ||||
4330 | CatchSwitch->addHandler(Handler); | ||||
4331 | I = CatchSwitch; | ||||
4332 | InstructionList.push_back(I); | ||||
4333 | break; | ||||
4334 | } | ||||
4335 | case bitc::FUNC_CODE_INST_CATCHPAD: | ||||
4336 | case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] | ||||
4337 | // We must have, at minimum, the outer scope and the number of arguments. | ||||
4338 | if (Record.size() < 2) | ||||
4339 | return error("Invalid record"); | ||||
4340 | |||||
4341 | unsigned Idx = 0; | ||||
4342 | |||||
4343 | Value *ParentPad = | ||||
4344 | getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); | ||||
4345 | |||||
4346 | unsigned NumArgOperands = Record[Idx++]; | ||||
4347 | |||||
4348 | SmallVector<Value *, 2> Args; | ||||
4349 | for (unsigned Op = 0; Op != NumArgOperands; ++Op) { | ||||
4350 | Value *Val; | ||||
4351 | if (getValueTypePair(Record, Idx, NextValueNo, Val)) | ||||
4352 | return error("Invalid record"); | ||||
4353 | Args.push_back(Val); | ||||
4354 | } | ||||
4355 | |||||
4356 | if (Record.size() != Idx) | ||||
4357 | return error("Invalid record"); | ||||
4358 | |||||
4359 | if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) | ||||
4360 | I = CleanupPadInst::Create(ParentPad, Args); | ||||
4361 | else | ||||
4362 | I = CatchPadInst::Create(ParentPad, Args); | ||||
4363 | InstructionList.push_back(I); | ||||
4364 | break; | ||||
4365 | } | ||||
4366 | case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] | ||||
4367 | // Check magic | ||||
4368 | if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { | ||||
4369 | // "New" SwitchInst format with case ranges. The changes to write this | ||||
4370 | // format were reverted but we still recognize bitcode that uses it. | ||||
4371 | // Hopefully someday we will have support for case ranges and can use | ||||
4372 | // this format again. | ||||
4373 | |||||
4374 | Type *OpTy = getTypeByID(Record[1]); | ||||
4375 | unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); | ||||
4376 | |||||
4377 | Value *Cond = getValue(Record, 2, NextValueNo, OpTy); | ||||
4378 | BasicBlock *Default = getBasicBlock(Record[3]); | ||||
4379 | if (!OpTy || !Cond || !Default) | ||||
4380 | return error("Invalid record"); | ||||
4381 | |||||
4382 | unsigned NumCases = Record[4]; | ||||
4383 | |||||
4384 | SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); | ||||
4385 | InstructionList.push_back(SI); | ||||
4386 | |||||
4387 | unsigned CurIdx = 5; | ||||
4388 | for (unsigned i = 0; i != NumCases; ++i) { | ||||
4389 | SmallVector<ConstantInt*, 1> CaseVals; | ||||
4390 | unsigned NumItems = Record[CurIdx++]; | ||||
4391 | for (unsigned ci = 0; ci != NumItems; ++ci) { | ||||
4392 | bool isSingleNumber = Record[CurIdx++]; | ||||
4393 | |||||
4394 | APInt Low; | ||||
4395 | unsigned ActiveWords = 1; | ||||
4396 | if (ValueBitWidth > 64) | ||||
4397 | ActiveWords = Record[CurIdx++]; | ||||
4398 | Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), | ||||
4399 | ValueBitWidth); | ||||
4400 | CurIdx += ActiveWords; | ||||
4401 | |||||
4402 | if (!isSingleNumber) { | ||||
4403 | ActiveWords = 1; | ||||
4404 | if (ValueBitWidth > 64) | ||||
4405 | ActiveWords = Record[CurIdx++]; | ||||
4406 | APInt High = readWideAPInt( | ||||
4407 | makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); | ||||
4408 | CurIdx += ActiveWords; | ||||
4409 | |||||
4410 | // FIXME: It is not clear whether values in the range should be | ||||
4411 | // compared as signed or unsigned values. The partially | ||||
4412 | // implemented changes that used this format in the past used | ||||
4413 | // unsigned comparisons. | ||||
4414 | for ( ; Low.ule(High); ++Low) | ||||
4415 | CaseVals.push_back(ConstantInt::get(Context, Low)); | ||||
4416 | } else | ||||
4417 | CaseVals.push_back(ConstantInt::get(Context, Low)); | ||||
4418 | } | ||||
4419 | BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); | ||||
4420 | for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), | ||||
4421 | cve = CaseVals.end(); cvi != cve; ++cvi) | ||||
4422 | SI->addCase(*cvi, DestBB); | ||||
4423 | } | ||||
4424 | I = SI; | ||||
4425 | break; | ||||
4426 | } | ||||
4427 | |||||
4428 | // Old SwitchInst format without case ranges. | ||||
4429 | |||||
4430 | if (Record.size() < 3 || (Record.size() & 1) == 0) | ||||
4431 | return error("Invalid record"); | ||||
4432 | Type *OpTy = getTypeByID(Record[0]); | ||||
4433 | Value *Cond = getValue(Record, 1, NextValueNo, OpTy); | ||||
4434 | BasicBlock *Default = getBasicBlock(Record[2]); | ||||
4435 | if (!OpTy || !Cond || !Default) | ||||
4436 | return error("Invalid record"); | ||||
4437 | unsigned NumCases = (Record.size()-3)/2; | ||||
4438 | SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); | ||||
4439 | InstructionList.push_back(SI); | ||||
4440 | for (unsigned i = 0, e = NumCases; i != e; ++i) { | ||||
4441 | ConstantInt *CaseVal = | ||||
4442 | dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); | ||||
4443 | BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); | ||||
4444 | if (!CaseVal || !DestBB) { | ||||
4445 | delete SI; | ||||
4446 | return error("Invalid record"); | ||||
4447 | } | ||||
4448 | SI->addCase(CaseVal, DestBB); | ||||
4449 | } | ||||
4450 | I = SI; | ||||
4451 | break; | ||||
4452 | } | ||||
4453 | case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] | ||||
4454 | if (Record.size() < 2) | ||||
4455 | return error("Invalid record"); | ||||
4456 | Type *OpTy = getTypeByID(Record[0]); | ||||
4457 | Value *Address = getValue(Record, 1, NextValueNo, OpTy); | ||||
4458 | if (!OpTy || !Address) | ||||
4459 | return error("Invalid record"); | ||||
4460 | unsigned NumDests = Record.size()-2; | ||||
4461 | IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); | ||||
4462 | InstructionList.push_back(IBI); | ||||
4463 | for (unsigned i = 0, e = NumDests; i != e; ++i) { | ||||
4464 | if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { | ||||
4465 | IBI->addDestination(DestBB); | ||||
4466 | } else { | ||||
4467 | delete IBI; | ||||
4468 | return error("Invalid record"); | ||||
4469 | } | ||||
4470 | } | ||||
4471 | I = IBI; | ||||
4472 | break; | ||||
4473 | } | ||||
4474 | |||||
4475 | case bitc::FUNC_CODE_INST_INVOKE: { | ||||
4476 | // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] | ||||
4477 | if (Record.size() < 4) | ||||
4478 | return error("Invalid record"); | ||||
4479 | unsigned OpNum = 0; | ||||
4480 | AttributeList PAL = getAttributes(Record[OpNum++]); | ||||
4481 | unsigned CCInfo = Record[OpNum++]; | ||||
4482 | BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); | ||||
4483 | BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); | ||||
4484 | |||||
4485 | FunctionType *FTy = nullptr; | ||||
4486 | FunctionType *FullFTy = nullptr; | ||||
4487 | if ((CCInfo >> 13) & 1) { | ||||
4488 | FullFTy = | ||||
4489 | dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++])); | ||||
4490 | if (!FullFTy) | ||||
4491 | return error("Explicit invoke type is not a function type"); | ||||
4492 | FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); | ||||
4493 | } | ||||
4494 | |||||
4495 | Value *Callee; | ||||
4496 | if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy)) | ||||
4497 | return error("Invalid record"); | ||||
4498 | |||||
4499 | PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); | ||||
4500 | if (!CalleeTy) | ||||
4501 | return error("Callee is not a pointer"); | ||||
4502 | if (!FTy) { | ||||
4503 | FullFTy = | ||||
4504 | dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType()); | ||||
4505 | if (!FullFTy) | ||||
4506 | return error("Callee is not of pointer to function type"); | ||||
4507 | FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); | ||||
4508 | } else if (getPointerElementFlatType(FullTy) != FTy) | ||||
4509 | return error("Explicit invoke type does not match pointee type of " | ||||
4510 | "callee operand"); | ||||
4511 | if (Record.size() < FTy->getNumParams() + OpNum) | ||||
4512 | return error("Insufficient operands to call"); | ||||
4513 | |||||
4514 | SmallVector<Value*, 16> Ops; | ||||
4515 | SmallVector<Type *, 16> ArgsFullTys; | ||||
4516 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { | ||||
4517 | Ops.push_back(getValue(Record, OpNum, NextValueNo, | ||||
4518 | FTy->getParamType(i))); | ||||
4519 | ArgsFullTys.push_back(FullFTy->getParamType(i)); | ||||
4520 | if (!Ops.back()) | ||||
4521 | return error("Invalid record"); | ||||
4522 | } | ||||
4523 | |||||
4524 | if (!FTy->isVarArg()) { | ||||
4525 | if (Record.size() != OpNum) | ||||
4526 | return error("Invalid record"); | ||||
4527 | } else { | ||||
4528 | // Read type/value pairs for varargs params. | ||||
4529 | while (OpNum != Record.size()) { | ||||
4530 | Value *Op; | ||||
4531 | Type *FullTy; | ||||
4532 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy)) | ||||
4533 | return error("Invalid record"); | ||||
4534 | Ops.push_back(Op); | ||||
4535 | ArgsFullTys.push_back(FullTy); | ||||
4536 | } | ||||
4537 | } | ||||
4538 | |||||
4539 | I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops, | ||||
4540 | OperandBundles); | ||||
4541 | FullTy = FullFTy->getReturnType(); | ||||
4542 | OperandBundles.clear(); | ||||
4543 | InstructionList.push_back(I); | ||||
4544 | cast<InvokeInst>(I)->setCallingConv( | ||||
4545 | static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); | ||||
4546 | cast<InvokeInst>(I)->setAttributes(PAL); | ||||
4547 | propagateByValTypes(cast<CallBase>(I), ArgsFullTys); | ||||
4548 | |||||
4549 | break; | ||||
4550 | } | ||||
4551 | case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] | ||||
4552 | unsigned Idx = 0; | ||||
4553 | Value *Val = nullptr; | ||||
4554 | if (getValueTypePair(Record, Idx, NextValueNo, Val)) | ||||
4555 | return error("Invalid record"); | ||||
4556 | I = ResumeInst::Create(Val); | ||||
4557 | InstructionList.push_back(I); | ||||
4558 | break; | ||||
4559 | } | ||||
4560 | case bitc::FUNC_CODE_INST_CALLBR: { | ||||
4561 | // CALLBR: [attr, cc, norm, transfs, fty, fnid, args] | ||||
4562 | unsigned OpNum = 0; | ||||
4563 | AttributeList PAL = getAttributes(Record[OpNum++]); | ||||
4564 | unsigned CCInfo = Record[OpNum++]; | ||||
4565 | |||||
4566 | BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]); | ||||
4567 | unsigned NumIndirectDests = Record[OpNum++]; | ||||
4568 | SmallVector<BasicBlock *, 16> IndirectDests; | ||||
4569 | for (unsigned i = 0, e = NumIndirectDests; i != e; ++i) | ||||
4570 | IndirectDests.push_back(getBasicBlock(Record[OpNum++])); | ||||
4571 | |||||
4572 | FunctionType *FTy = nullptr; | ||||
4573 | FunctionType *FullFTy = nullptr; | ||||
4574 | if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { | ||||
4575 | FullFTy = | ||||
4576 | dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++])); | ||||
4577 | if (!FullFTy) | ||||
4578 | return error("Explicit call type is not a function type"); | ||||
4579 | FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); | ||||
4580 | } | ||||
4581 | |||||
4582 | Value *Callee; | ||||
4583 | if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy)) | ||||
4584 | return error("Invalid record"); | ||||
4585 | |||||
4586 | PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); | ||||
4587 | if (!OpTy) | ||||
4588 | return error("Callee is not a pointer type"); | ||||
4589 | if (!FTy) { | ||||
4590 | FullFTy = | ||||
4591 | dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType()); | ||||
4592 | if (!FullFTy) | ||||
4593 | return error("Callee is not of pointer to function type"); | ||||
4594 | FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); | ||||
4595 | } else if (getPointerElementFlatType(FullTy) != FTy) | ||||
4596 | return error("Explicit call type does not match pointee type of " | ||||
4597 | "callee operand"); | ||||
4598 | if (Record.size() < FTy->getNumParams() + OpNum) | ||||
4599 | return error("Insufficient operands to call"); | ||||
4600 | |||||
4601 | SmallVector<Value*, 16> Args; | ||||
4602 | // Read the fixed params. | ||||
4603 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { | ||||
4604 | if (FTy->getParamType(i)->isLabelTy()) | ||||
4605 | Args.push_back(getBasicBlock(Record[OpNum])); | ||||
4606 | else | ||||
4607 | Args.push_back(getValue(Record, OpNum, NextValueNo, | ||||
4608 | FTy->getParamType(i))); | ||||
4609 | if (!Args.back()) | ||||
4610 | return error("Invalid record"); | ||||
4611 | } | ||||
4612 | |||||
4613 | // Read type/value pairs for varargs params. | ||||
4614 | if (!FTy->isVarArg()) { | ||||
4615 | if (OpNum != Record.size()) | ||||
4616 | return error("Invalid record"); | ||||
4617 | } else { | ||||
4618 | while (OpNum != Record.size()) { | ||||
4619 | Value *Op; | ||||
4620 | if (getValueTypePair(Record, OpNum, NextValueNo, Op)) | ||||
4621 | return error("Invalid record"); | ||||
4622 | Args.push_back(Op); | ||||
4623 | } | ||||
4624 | } | ||||
4625 | |||||
4626 | I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args, | ||||
4627 | OperandBundles); | ||||
4628 | FullTy = FullFTy->getReturnType(); | ||||
4629 | OperandBundles.clear(); | ||||
4630 | InstructionList.push_back(I); | ||||
4631 | cast<CallBrInst>(I)->setCallingConv( | ||||
4632 | static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); | ||||
4633 | cast<CallBrInst>(I)->setAttributes(PAL); | ||||
4634 | break; | ||||
4635 | } | ||||
4636 | case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE | ||||
4637 | I = new UnreachableInst(Context); | ||||
4638 | InstructionList.push_back(I); | ||||
4639 | break; | ||||
4640 | case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] | ||||
4641 | if (Record.size() < 1) | ||||
4642 | return error("Invalid record"); | ||||
4643 | // The first record specifies the type. | ||||
4644 | FullTy = getFullyStructuredTypeByID(Record[0]); | ||||
4645 | Type *Ty = flattenPointerTypes(FullTy); | ||||
4646 | if (!Ty) | ||||
4647 | return error("Invalid record"); | ||||
4648 | |||||
4649 | // Phi arguments are pairs of records of [value, basic block]. | ||||
4650 | // There is an optional final record for fast-math-flags if this phi has a | ||||
4651 | // floating-point type. | ||||
4652 | size_t NumArgs = (Record.size() - 1) / 2; | ||||
4653 | PHINode *PN = PHINode::Create(Ty, NumArgs); | ||||
4654 | if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) | ||||
4655 | return error("Invalid record"); | ||||
4656 | InstructionList.push_back(PN); | ||||
4657 | |||||
4658 | for (unsigned i = 0; i != NumArgs; i++) { | ||||
4659 | Value *V; | ||||
4660 | // With the new function encoding, it is possible that operands have | ||||
4661 | // negative IDs (for forward references). Use a signed VBR | ||||
4662 | // representation to keep the encoding small. | ||||
4663 | if (UseRelativeIDs) | ||||
4664 | V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty); | ||||
4665 | else | ||||
4666 | V = getValue(Record, i * 2 + 1, NextValueNo, Ty); | ||||
4667 | BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]); | ||||
4668 | if (!V || !BB) | ||||
4669 | return error("Invalid record"); | ||||
4670 | PN->addIncoming(V, BB); | ||||
4671 | } | ||||
4672 | I = PN; | ||||
4673 | |||||
4674 | // If there are an even number of records, the final record must be FMF. | ||||
4675 | if (Record.size() % 2 == 0) { | ||||
4676 | assert(isa<FPMathOperator>(I) && "Unexpected phi type")((isa<FPMathOperator>(I) && "Unexpected phi type" ) ? static_cast<void> (0) : __assert_fail ("isa<FPMathOperator>(I) && \"Unexpected phi type\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 4676, __PRETTY_FUNCTION__)); | ||||
4677 | FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]); | ||||
4678 | if (FMF.any()) | ||||
4679 | I->setFastMathFlags(FMF); | ||||
4680 | } | ||||
4681 | |||||
4682 | break; | ||||
4683 | } | ||||
4684 | |||||
4685 | case bitc::FUNC_CODE_INST_LANDINGPAD: | ||||
4686 | case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { | ||||
4687 | // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] | ||||
4688 | unsigned Idx = 0; | ||||
4689 | if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { | ||||
4690 | if (Record.size() < 3) | ||||
4691 | return error("Invalid record"); | ||||
4692 | } else { | ||||
4693 | assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD)((BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) ? static_cast <void> (0) : __assert_fail ("BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 4693, __PRETTY_FUNCTION__)); | ||||
4694 | if (Record.size() < 4) | ||||
4695 | return error("Invalid record"); | ||||
4696 | } | ||||
4697 | FullTy = getFullyStructuredTypeByID(Record[Idx++]); | ||||
4698 | Type *Ty = flattenPointerTypes(FullTy); | ||||
4699 | if (!Ty) | ||||
4700 | return error("Invalid record"); | ||||
4701 | if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { | ||||
4702 | Value *PersFn = nullptr; | ||||
4703 | if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) | ||||
4704 | return error("Invalid record"); | ||||
4705 | |||||
4706 | if (!F->hasPersonalityFn()) | ||||
4707 | F->setPersonalityFn(cast<Constant>(PersFn)); | ||||
4708 | else if (F->getPersonalityFn() != cast<Constant>(PersFn)) | ||||
4709 | return error("Personality function mismatch"); | ||||
4710 | } | ||||
4711 | |||||
4712 | bool IsCleanup = !!Record[Idx++]; | ||||
4713 | unsigned NumClauses = Record[Idx++]; | ||||
4714 | LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); | ||||
4715 | LP->setCleanup(IsCleanup); | ||||
4716 | for (unsigned J = 0; J != NumClauses; ++J) { | ||||
4717 | LandingPadInst::ClauseType CT = | ||||
4718 | LandingPadInst::ClauseType(Record[Idx++]); (void)CT; | ||||
4719 | Value *Val; | ||||
4720 | |||||
4721 | if (getValueTypePair(Record, Idx, NextValueNo, Val)) { | ||||
4722 | delete LP; | ||||
4723 | return error("Invalid record"); | ||||
4724 | } | ||||
4725 | |||||
4726 | assert((CT != LandingPadInst::Catch ||(((CT != LandingPadInst::Catch || !isa<ArrayType>(Val-> getType())) && "Catch clause has a invalid type!") ? static_cast <void> (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 4728, __PRETTY_FUNCTION__)) | ||||
4727 | !isa<ArrayType>(Val->getType())) &&(((CT != LandingPadInst::Catch || !isa<ArrayType>(Val-> getType())) && "Catch clause has a invalid type!") ? static_cast <void> (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 4728, __PRETTY_FUNCTION__)) | ||||
4728 | "Catch clause has a invalid type!")(((CT != LandingPadInst::Catch || !isa<ArrayType>(Val-> getType())) && "Catch clause has a invalid type!") ? static_cast <void> (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 4728, __PRETTY_FUNCTION__)); | ||||
4729 | assert((CT != LandingPadInst::Filter ||(((CT != LandingPadInst::Filter || isa<ArrayType>(Val-> getType())) && "Filter clause has invalid type!") ? static_cast <void> (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 4731, __PRETTY_FUNCTION__)) | ||||
4730 | isa<ArrayType>(Val->getType())) &&(((CT != LandingPadInst::Filter || isa<ArrayType>(Val-> getType())) && "Filter clause has invalid type!") ? static_cast <void> (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 4731, __PRETTY_FUNCTION__)) | ||||
4731 | "Filter clause has invalid type!")(((CT != LandingPadInst::Filter || isa<ArrayType>(Val-> getType())) && "Filter clause has invalid type!") ? static_cast <void> (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 4731, __PRETTY_FUNCTION__)); | ||||
4732 | LP->addClause(cast<Constant>(Val)); | ||||
4733 | } | ||||
4734 | |||||
4735 | I = LP; | ||||
4736 | InstructionList.push_back(I); | ||||
4737 | break; | ||||
4738 | } | ||||
4739 | |||||
4740 | case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] | ||||
4741 | if (Record.size() != 4) | ||||
4742 | return error("Invalid record"); | ||||
4743 | uint64_t AlignRecord = Record[3]; | ||||
4744 | const uint64_t InAllocaMask = uint64_t(1) << 5; | ||||
4745 | const uint64_t ExplicitTypeMask = uint64_t(1) << 6; | ||||
4746 | const uint64_t SwiftErrorMask = uint64_t(1) << 7; | ||||
4747 | const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask | | ||||
4748 | SwiftErrorMask; | ||||
4749 | bool InAlloca = AlignRecord & InAllocaMask; | ||||
4750 | bool SwiftError = AlignRecord & SwiftErrorMask; | ||||
4751 | FullTy = getFullyStructuredTypeByID(Record[0]); | ||||
4752 | Type *Ty = flattenPointerTypes(FullTy); | ||||
4753 | if ((AlignRecord & ExplicitTypeMask) == 0) { | ||||
4754 | auto *PTy = dyn_cast_or_null<PointerType>(Ty); | ||||
4755 | if (!PTy) | ||||
4756 | return error("Old-style alloca with a non-pointer type"); | ||||
4757 | std::tie(FullTy, Ty) = getPointerElementTypes(FullTy); | ||||
4758 | } | ||||
4759 | Type *OpTy = getTypeByID(Record[1]); | ||||
4760 | Value *Size = getFnValueByID(Record[2], OpTy); | ||||
4761 | MaybeAlign Align; | ||||
4762 | if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { | ||||
4763 | return Err; | ||||
4764 | } | ||||
4765 | if (!Ty || !Size) | ||||
4766 | return error("Invalid record"); | ||||
4767 | |||||
4768 | // FIXME: Make this an optional field. | ||||
4769 | const DataLayout &DL = TheModule->getDataLayout(); | ||||
4770 | unsigned AS = DL.getAllocaAddrSpace(); | ||||
4771 | |||||
4772 | AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align); | ||||
4773 | AI->setUsedWithInAlloca(InAlloca); | ||||
4774 | AI->setSwiftError(SwiftError); | ||||
4775 | I = AI; | ||||
4776 | FullTy = PointerType::get(FullTy, AS); | ||||
4777 | InstructionList.push_back(I); | ||||
4778 | break; | ||||
4779 | } | ||||
4780 | case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] | ||||
4781 | unsigned OpNum = 0; | ||||
4782 | Value *Op; | ||||
4783 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) || | ||||
4784 | (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) | ||||
4785 | return error("Invalid record"); | ||||
4786 | |||||
4787 | if (!isa<PointerType>(Op->getType())) | ||||
4788 | return error("Load operand is not a pointer type"); | ||||
4789 | |||||
4790 | Type *Ty = nullptr; | ||||
4791 | if (OpNum + 3 == Record.size()) { | ||||
4792 | FullTy = getFullyStructuredTypeByID(Record[OpNum++]); | ||||
4793 | Ty = flattenPointerTypes(FullTy); | ||||
4794 | } else | ||||
4795 | std::tie(FullTy, Ty) = getPointerElementTypes(FullTy); | ||||
4796 | |||||
4797 | if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) | ||||
4798 | return Err; | ||||
4799 | |||||
4800 | MaybeAlign Align; | ||||
4801 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) | ||||
4802 | return Err; | ||||
4803 | I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); | ||||
4804 | InstructionList.push_back(I); | ||||
4805 | break; | ||||
4806 | } | ||||
4807 | case bitc::FUNC_CODE_INST_LOADATOMIC: { | ||||
4808 | // LOADATOMIC: [opty, op, align, vol, ordering, ssid] | ||||
4809 | unsigned OpNum = 0; | ||||
4810 | Value *Op; | ||||
4811 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) || | ||||
4812 | (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) | ||||
4813 | return error("Invalid record"); | ||||
4814 | |||||
4815 | if (!isa<PointerType>(Op->getType())) | ||||
4816 | return error("Load operand is not a pointer type"); | ||||
4817 | |||||
4818 | Type *Ty = nullptr; | ||||
4819 | if (OpNum + 5 == Record.size()) { | ||||
4820 | FullTy = getFullyStructuredTypeByID(Record[OpNum++]); | ||||
4821 | Ty = flattenPointerTypes(FullTy); | ||||
4822 | } else | ||||
4823 | std::tie(FullTy, Ty) = getPointerElementTypes(FullTy); | ||||
4824 | |||||
4825 | if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) | ||||
4826 | return Err; | ||||
4827 | |||||
4828 | AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); | ||||
4829 | if (Ordering == AtomicOrdering::NotAtomic || | ||||
4830 | Ordering == AtomicOrdering::Release || | ||||
4831 | Ordering == AtomicOrdering::AcquireRelease) | ||||
4832 | return error("Invalid record"); | ||||
4833 | if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) | ||||
4834 | return error("Invalid record"); | ||||
4835 | SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); | ||||
4836 | |||||
4837 | MaybeAlign Align; | ||||
4838 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) | ||||
4839 | return Err; | ||||
4840 | I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align, Ordering, SSID); | ||||
4841 | InstructionList.push_back(I); | ||||
4842 | break; | ||||
4843 | } | ||||
4844 | case bitc::FUNC_CODE_INST_STORE: | ||||
4845 | case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] | ||||
4846 | unsigned OpNum = 0; | ||||
4847 | Value *Val, *Ptr; | ||||
4848 | Type *FullTy; | ||||
4849 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) || | ||||
4850 | (BitCode == bitc::FUNC_CODE_INST_STORE | ||||
4851 | ? getValueTypePair(Record, OpNum, NextValueNo, Val) | ||||
4852 | : popValue(Record, OpNum, NextValueNo, | ||||
4853 | getPointerElementFlatType(FullTy), Val)) || | ||||
4854 | OpNum + 2 != Record.size()) | ||||
4855 | return error("Invalid record"); | ||||
4856 | |||||
4857 | if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) | ||||
4858 | return Err; | ||||
4859 | MaybeAlign Align; | ||||
4860 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) | ||||
4861 | return Err; | ||||
4862 | I = new StoreInst(Val, Ptr, Record[OpNum + 1], Align); | ||||
4863 | InstructionList.push_back(I); | ||||
4864 | break; | ||||
4865 | } | ||||
4866 | case bitc::FUNC_CODE_INST_STOREATOMIC: | ||||
4867 | case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { | ||||
4868 | // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] | ||||
4869 | unsigned OpNum = 0; | ||||
4870 | Value *Val, *Ptr; | ||||
4871 | Type *FullTy; | ||||
4872 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) || | ||||
4873 | !isa<PointerType>(Ptr->getType()) || | ||||
4874 | (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC | ||||
4875 | ? getValueTypePair(Record, OpNum, NextValueNo, Val) | ||||
4876 | : popValue(Record, OpNum, NextValueNo, | ||||
4877 | getPointerElementFlatType(FullTy), Val)) || | ||||
4878 | OpNum + 4 != Record.size()) | ||||
4879 | return error("Invalid record"); | ||||
4880 | |||||
4881 | if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) | ||||
4882 | return Err; | ||||
4883 | AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); | ||||
4884 | if (Ordering == AtomicOrdering::NotAtomic || | ||||
4885 | Ordering == AtomicOrdering::Acquire || | ||||
4886 | Ordering == AtomicOrdering::AcquireRelease) | ||||
4887 | return error("Invalid record"); | ||||
4888 | SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); | ||||
4889 | if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) | ||||
4890 | return error("Invalid record"); | ||||
4891 | |||||
4892 | MaybeAlign Align; | ||||
4893 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) | ||||
4894 | return Err; | ||||
4895 | I = new StoreInst(Val, Ptr, Record[OpNum + 1], Align, Ordering, SSID); | ||||
4896 | InstructionList.push_back(I); | ||||
4897 | break; | ||||
4898 | } | ||||
4899 | case bitc::FUNC_CODE_INST_CMPXCHG_OLD: | ||||
4900 | case bitc::FUNC_CODE_INST_CMPXCHG: { | ||||
4901 | // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid, | ||||
4902 | // failureordering?, isweak?] | ||||
4903 | unsigned OpNum = 0; | ||||
4904 | Value *Ptr, *Cmp, *New; | ||||
4905 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy)) | ||||
4906 | return error("Invalid record"); | ||||
4907 | |||||
4908 | if (!isa<PointerType>(Ptr->getType())) | ||||
4909 | return error("Cmpxchg operand is not a pointer type"); | ||||
4910 | |||||
4911 | if (BitCode == bitc::FUNC_CODE_INST_CMPXCHG) { | ||||
4912 | if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, &FullTy)) | ||||
4913 | return error("Invalid record"); | ||||
4914 | } else if (popValue(Record, OpNum, NextValueNo, | ||||
4915 | getPointerElementFlatType(FullTy), Cmp)) | ||||
4916 | return error("Invalid record"); | ||||
4917 | else | ||||
4918 | FullTy = cast<PointerType>(FullTy)->getElementType(); | ||||
4919 | |||||
4920 | if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || | ||||
4921 | Record.size() < OpNum + 3 || Record.size() > OpNum + 5) | ||||
4922 | return error("Invalid record"); | ||||
4923 | |||||
4924 | AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); | ||||
4925 | if (SuccessOrdering == AtomicOrdering::NotAtomic || | ||||
4926 | SuccessOrdering == AtomicOrdering::Unordered) | ||||
4927 | return error("Invalid record"); | ||||
4928 | SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); | ||||
4929 | |||||
4930 | if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) | ||||
4931 | return Err; | ||||
4932 | AtomicOrdering FailureOrdering; | ||||
4933 | if (Record.size() < 7) | ||||
4934 | FailureOrdering = | ||||
4935 | AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); | ||||
4936 | else | ||||
4937 | FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); | ||||
4938 | |||||
4939 | I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, | ||||
4940 | SSID); | ||||
4941 | FullTy = StructType::get(Context, {FullTy, Type::getInt1Ty(Context)}); | ||||
4942 | cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); | ||||
4943 | |||||
4944 | if (Record.size() < 8) { | ||||
4945 | // Before weak cmpxchgs existed, the instruction simply returned the | ||||
4946 | // value loaded from memory, so bitcode files from that era will be | ||||
4947 | // expecting the first component of a modern cmpxchg. | ||||
4948 | CurBB->getInstList().push_back(I); | ||||
4949 | I = ExtractValueInst::Create(I, 0); | ||||
4950 | FullTy = cast<StructType>(FullTy)->getElementType(0); | ||||
4951 | } else { | ||||
4952 | cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); | ||||
4953 | } | ||||
4954 | |||||
4955 | InstructionList.push_back(I); | ||||
4956 | break; | ||||
4957 | } | ||||
4958 | case bitc::FUNC_CODE_INST_ATOMICRMW: { | ||||
4959 | // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid] | ||||
4960 | unsigned OpNum = 0; | ||||
4961 | Value *Ptr, *Val; | ||||
4962 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) || | ||||
4963 | !isa<PointerType>(Ptr->getType()) || | ||||
4964 | popValue(Record, OpNum, NextValueNo, | ||||
4965 | getPointerElementFlatType(FullTy), Val) || | ||||
4966 | OpNum + 4 != Record.size()) | ||||
4967 | return error("Invalid record"); | ||||
4968 | AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); | ||||
4969 | if (Operation < AtomicRMWInst::FIRST_BINOP || | ||||
4970 | Operation > AtomicRMWInst::LAST_BINOP) | ||||
4971 | return error("Invalid record"); | ||||
4972 | AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); | ||||
4973 | if (Ordering == AtomicOrdering::NotAtomic || | ||||
4974 | Ordering == AtomicOrdering::Unordered) | ||||
4975 | return error("Invalid record"); | ||||
4976 | SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); | ||||
4977 | I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID); | ||||
4978 | FullTy = getPointerElementFlatType(FullTy); | ||||
4979 | cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); | ||||
4980 | InstructionList.push_back(I); | ||||
4981 | break; | ||||
4982 | } | ||||
4983 | case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] | ||||
4984 | if (2 != Record.size()) | ||||
4985 | return error("Invalid record"); | ||||
4986 | AtomicOrdering Ordering = getDecodedOrdering(Record[0]); | ||||
4987 | if (Ordering == AtomicOrdering::NotAtomic || | ||||
4988 | Ordering == AtomicOrdering::Unordered || | ||||
4989 | Ordering == AtomicOrdering::Monotonic) | ||||
4990 | return error("Invalid record"); | ||||
4991 | SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); | ||||
4992 | I = new FenceInst(Context, Ordering, SSID); | ||||
4993 | InstructionList.push_back(I); | ||||
4994 | break; | ||||
4995 | } | ||||
4996 | case bitc::FUNC_CODE_INST_CALL: { | ||||
4997 | // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] | ||||
4998 | if (Record.size() < 3) | ||||
4999 | return error("Invalid record"); | ||||
5000 | |||||
5001 | unsigned OpNum = 0; | ||||
5002 | AttributeList PAL = getAttributes(Record[OpNum++]); | ||||
5003 | unsigned CCInfo = Record[OpNum++]; | ||||
5004 | |||||
5005 | FastMathFlags FMF; | ||||
5006 | if ((CCInfo >> bitc::CALL_FMF) & 1) { | ||||
5007 | FMF = getDecodedFastMathFlags(Record[OpNum++]); | ||||
5008 | if (!FMF.any()) | ||||
5009 | return error("Fast math flags indicator set for call with no FMF"); | ||||
5010 | } | ||||
5011 | |||||
5012 | FunctionType *FTy = nullptr; | ||||
5013 | FunctionType *FullFTy = nullptr; | ||||
5014 | if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { | ||||
5015 | FullFTy = | ||||
5016 | dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++])); | ||||
5017 | if (!FullFTy) | ||||
5018 | return error("Explicit call type is not a function type"); | ||||
5019 | FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); | ||||
5020 | } | ||||
5021 | |||||
5022 | Value *Callee; | ||||
5023 | if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy)) | ||||
5024 | return error("Invalid record"); | ||||
5025 | |||||
5026 | PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); | ||||
5027 | if (!OpTy) | ||||
5028 | return error("Callee is not a pointer type"); | ||||
5029 | if (!FTy) { | ||||
5030 | FullFTy = | ||||
5031 | dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType()); | ||||
5032 | if (!FullFTy) | ||||
5033 | return error("Callee is not of pointer to function type"); | ||||
5034 | FTy = cast<FunctionType>(flattenPointerTypes(FullFTy)); | ||||
5035 | } else if (getPointerElementFlatType(FullTy) != FTy) | ||||
5036 | return error("Explicit call type does not match pointee type of " | ||||
5037 | "callee operand"); | ||||
5038 | if (Record.size() < FTy->getNumParams() + OpNum) | ||||
5039 | return error("Insufficient operands to call"); | ||||
5040 | |||||
5041 | SmallVector<Value*, 16> Args; | ||||
5042 | SmallVector<Type*, 16> ArgsFullTys; | ||||
5043 | // Read the fixed params. | ||||
5044 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { | ||||
5045 | if (FTy->getParamType(i)->isLabelTy()) | ||||
5046 | Args.push_back(getBasicBlock(Record[OpNum])); | ||||
5047 | else | ||||
5048 | Args.push_back(getValue(Record, OpNum, NextValueNo, | ||||
5049 | FTy->getParamType(i))); | ||||
5050 | ArgsFullTys.push_back(FullFTy->getParamType(i)); | ||||
5051 | if (!Args.back()) | ||||
5052 | return error("Invalid record"); | ||||
5053 | } | ||||
5054 | |||||
5055 | // Read type/value pairs for varargs params. | ||||
5056 | if (!FTy->isVarArg()) { | ||||
5057 | if (OpNum != Record.size()) | ||||
5058 | return error("Invalid record"); | ||||
5059 | } else { | ||||
5060 | while (OpNum != Record.size()) { | ||||
5061 | Value *Op; | ||||
5062 | Type *FullTy; | ||||
5063 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy)) | ||||
5064 | return error("Invalid record"); | ||||
5065 | Args.push_back(Op); | ||||
5066 | ArgsFullTys.push_back(FullTy); | ||||
5067 | } | ||||
5068 | } | ||||
5069 | |||||
5070 | I = CallInst::Create(FTy, Callee, Args, OperandBundles); | ||||
5071 | FullTy = FullFTy->getReturnType(); | ||||
5072 | OperandBundles.clear(); | ||||
5073 | InstructionList.push_back(I); | ||||
5074 | cast<CallInst>(I)->setCallingConv( | ||||
5075 | static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); | ||||
5076 | CallInst::TailCallKind TCK = CallInst::TCK_None; | ||||
5077 | if (CCInfo & 1 << bitc::CALL_TAIL) | ||||
5078 | TCK = CallInst::TCK_Tail; | ||||
5079 | if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) | ||||
5080 | TCK = CallInst::TCK_MustTail; | ||||
5081 | if (CCInfo & (1 << bitc::CALL_NOTAIL)) | ||||
5082 | TCK = CallInst::TCK_NoTail; | ||||
5083 | cast<CallInst>(I)->setTailCallKind(TCK); | ||||
5084 | cast<CallInst>(I)->setAttributes(PAL); | ||||
5085 | propagateByValTypes(cast<CallBase>(I), ArgsFullTys); | ||||
5086 | if (FMF.any()) { | ||||
5087 | if (!isa<FPMathOperator>(I)) | ||||
5088 | return error("Fast-math-flags specified for call without " | ||||
5089 | "floating-point scalar or vector return type"); | ||||
5090 | I->setFastMathFlags(FMF); | ||||
5091 | } | ||||
5092 | break; | ||||
5093 | } | ||||
5094 | case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] | ||||
5095 | if (Record.size() < 3) | ||||
5096 | return error("Invalid record"); | ||||
5097 | Type *OpTy = getTypeByID(Record[0]); | ||||
5098 | Value *Op = getValue(Record, 1, NextValueNo, OpTy); | ||||
5099 | FullTy = getFullyStructuredTypeByID(Record[2]); | ||||
5100 | Type *ResTy = flattenPointerTypes(FullTy); | ||||
5101 | if (!OpTy || !Op || !ResTy) | ||||
5102 | return error("Invalid record"); | ||||
5103 | I = new VAArgInst(Op, ResTy); | ||||
5104 | InstructionList.push_back(I); | ||||
5105 | break; | ||||
5106 | } | ||||
5107 | |||||
5108 | case bitc::FUNC_CODE_OPERAND_BUNDLE: { | ||||
5109 | // A call or an invoke can be optionally prefixed with some variable | ||||
5110 | // number of operand bundle blocks. These blocks are read into | ||||
5111 | // OperandBundles and consumed at the next call or invoke instruction. | ||||
5112 | |||||
5113 | if (Record.size() < 1 || Record[0] >= BundleTags.size()) | ||||
5114 | return error("Invalid record"); | ||||
5115 | |||||
5116 | std::vector<Value *> Inputs; | ||||
5117 | |||||
5118 | unsigned OpNum = 1; | ||||
5119 | while (OpNum != Record.size()) { | ||||
5120 | Value *Op; | ||||
5121 | if (getValueTypePair(Record, OpNum, NextValueNo, Op)) | ||||
5122 | return error("Invalid record"); | ||||
5123 | Inputs.push_back(Op); | ||||
5124 | } | ||||
5125 | |||||
5126 | OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); | ||||
5127 | continue; | ||||
5128 | } | ||||
5129 | |||||
5130 | case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval] | ||||
5131 | unsigned OpNum = 0; | ||||
5132 | Value *Op = nullptr; | ||||
5133 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy)) | ||||
5134 | return error("Invalid record"); | ||||
5135 | if (OpNum != Record.size()) | ||||
5136 | return error("Invalid record"); | ||||
5137 | |||||
5138 | I = new FreezeInst(Op); | ||||
5139 | InstructionList.push_back(I); | ||||
5140 | break; | ||||
5141 | } | ||||
5142 | } | ||||
5143 | |||||
5144 | // Add instruction to end of current BB. If there is no current BB, reject | ||||
5145 | // this file. | ||||
5146 | if (!CurBB) { | ||||
5147 | I->deleteValue(); | ||||
5148 | return error("Invalid instruction with no BB"); | ||||
5149 | } | ||||
5150 | if (!OperandBundles.empty()) { | ||||
5151 | I->deleteValue(); | ||||
5152 | return error("Operand bundles found with no consumer"); | ||||
5153 | } | ||||
5154 | CurBB->getInstList().push_back(I); | ||||
5155 | |||||
5156 | // If this was a terminator instruction, move to the next block. | ||||
5157 | if (I->isTerminator()) { | ||||
5158 | ++CurBBNo; | ||||
5159 | CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; | ||||
5160 | } | ||||
5161 | |||||
5162 | // Non-void values get registered in the value table for future use. | ||||
5163 | if (!I->getType()->isVoidTy()) { | ||||
5164 | if (!FullTy) { | ||||
5165 | FullTy = I->getType(); | ||||
5166 | assert(((!FullTy->isPointerTy() && !isa<StructType> (FullTy) && !isa<ArrayType>(FullTy) && ( !isa<VectorType>(FullTy) || FullTy->getVectorElementType ()->isFloatingPointTy() || FullTy->getVectorElementType ()->isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque " "pointer type") ? static_cast<void> (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || FullTy->getVectorElementType()->isFloatingPointTy() || FullTy->getVectorElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5173, __PRETTY_FUNCTION__)) | ||||
5167 | !FullTy->isPointerTy() && !isa<StructType>(FullTy) &&((!FullTy->isPointerTy() && !isa<StructType> (FullTy) && !isa<ArrayType>(FullTy) && ( !isa<VectorType>(FullTy) || FullTy->getVectorElementType ()->isFloatingPointTy() || FullTy->getVectorElementType ()->isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque " "pointer type") ? static_cast<void> (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || FullTy->getVectorElementType()->isFloatingPointTy() || FullTy->getVectorElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5173, __PRETTY_FUNCTION__)) | ||||
5168 | !isa<ArrayType>(FullTy) &&((!FullTy->isPointerTy() && !isa<StructType> (FullTy) && !isa<ArrayType>(FullTy) && ( !isa<VectorType>(FullTy) || FullTy->getVectorElementType ()->isFloatingPointTy() || FullTy->getVectorElementType ()->isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque " "pointer type") ? static_cast<void> (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || FullTy->getVectorElementType()->isFloatingPointTy() || FullTy->getVectorElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5173, __PRETTY_FUNCTION__)) | ||||
5169 | (!isa<VectorType>(FullTy) ||((!FullTy->isPointerTy() && !isa<StructType> (FullTy) && !isa<ArrayType>(FullTy) && ( !isa<VectorType>(FullTy) || FullTy->getVectorElementType ()->isFloatingPointTy() || FullTy->getVectorElementType ()->isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque " "pointer type") ? static_cast<void> (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || FullTy->getVectorElementType()->isFloatingPointTy() || FullTy->getVectorElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5173, __PRETTY_FUNCTION__)) | ||||
5170 | FullTy->getVectorElementType()->isFloatingPointTy() ||((!FullTy->isPointerTy() && !isa<StructType> (FullTy) && !isa<ArrayType>(FullTy) && ( !isa<VectorType>(FullTy) || FullTy->getVectorElementType ()->isFloatingPointTy() || FullTy->getVectorElementType ()->isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque " "pointer type") ? static_cast<void> (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || FullTy->getVectorElementType()->isFloatingPointTy() || FullTy->getVectorElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5173, __PRETTY_FUNCTION__)) | ||||
5171 | FullTy->getVectorElementType()->isIntegerTy()) &&((!FullTy->isPointerTy() && !isa<StructType> (FullTy) && !isa<ArrayType>(FullTy) && ( !isa<VectorType>(FullTy) || FullTy->getVectorElementType ()->isFloatingPointTy() || FullTy->getVectorElementType ()->isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque " "pointer type") ? static_cast<void> (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || FullTy->getVectorElementType()->isFloatingPointTy() || FullTy->getVectorElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5173, __PRETTY_FUNCTION__)) | ||||
5172 | "Structured types must be assigned with corresponding non-opaque "((!FullTy->isPointerTy() && !isa<StructType> (FullTy) && !isa<ArrayType>(FullTy) && ( !isa<VectorType>(FullTy) || FullTy->getVectorElementType ()->isFloatingPointTy() || FullTy->getVectorElementType ()->isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque " "pointer type") ? static_cast<void> (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || FullTy->getVectorElementType()->isFloatingPointTy() || FullTy->getVectorElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5173, __PRETTY_FUNCTION__)) | ||||
5173 | "pointer type")((!FullTy->isPointerTy() && !isa<StructType> (FullTy) && !isa<ArrayType>(FullTy) && ( !isa<VectorType>(FullTy) || FullTy->getVectorElementType ()->isFloatingPointTy() || FullTy->getVectorElementType ()->isIntegerTy()) && "Structured types must be assigned with corresponding non-opaque " "pointer type") ? static_cast<void> (0) : __assert_fail ("!FullTy->isPointerTy() && !isa<StructType>(FullTy) && !isa<ArrayType>(FullTy) && (!isa<VectorType>(FullTy) || FullTy->getVectorElementType()->isFloatingPointTy() || FullTy->getVectorElementType()->isIntegerTy()) && \"Structured types must be assigned with corresponding non-opaque \" \"pointer type\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5173, __PRETTY_FUNCTION__)); | ||||
5174 | } | ||||
5175 | |||||
5176 | assert(I->getType() == flattenPointerTypes(FullTy) &&((I->getType() == flattenPointerTypes(FullTy) && "Incorrect fully structured type provided for Instruction" ) ? static_cast<void> (0) : __assert_fail ("I->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for Instruction\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5177, __PRETTY_FUNCTION__)) | ||||
5177 | "Incorrect fully structured type provided for Instruction")((I->getType() == flattenPointerTypes(FullTy) && "Incorrect fully structured type provided for Instruction" ) ? static_cast<void> (0) : __assert_fail ("I->getType() == flattenPointerTypes(FullTy) && \"Incorrect fully structured type provided for Instruction\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5177, __PRETTY_FUNCTION__)); | ||||
5178 | ValueList.assignValue(I, NextValueNo++, FullTy); | ||||
5179 | } | ||||
5180 | } | ||||
5181 | |||||
5182 | OutOfRecordLoop: | ||||
5183 | |||||
5184 | if (!OperandBundles.empty()) | ||||
5185 | return error("Operand bundles found with no consumer"); | ||||
5186 | |||||
5187 | // Check the function list for unresolved values. | ||||
5188 | if (Argument *A = dyn_cast<Argument>(ValueList.back())) { | ||||
5189 | if (!A->getParent()) { | ||||
5190 | // We found at least one unresolved value. Nuke them all to avoid leaks. | ||||
5191 | for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ | ||||
5192 | if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { | ||||
5193 | A->replaceAllUsesWith(UndefValue::get(A->getType())); | ||||
5194 | delete A; | ||||
5195 | } | ||||
5196 | } | ||||
5197 | return error("Never resolved value found in function"); | ||||
5198 | } | ||||
5199 | } | ||||
5200 | |||||
5201 | // Unexpected unresolved metadata about to be dropped. | ||||
5202 | if (MDLoader->hasFwdRefs()) | ||||
5203 | return error("Invalid function metadata: outgoing forward refs"); | ||||
5204 | |||||
5205 | // Trim the value list down to the size it was before we parsed this function. | ||||
5206 | ValueList.shrinkTo(ModuleValueListSize); | ||||
5207 | MDLoader->shrinkTo(ModuleMDLoaderSize); | ||||
5208 | std::vector<BasicBlock*>().swap(FunctionBBs); | ||||
5209 | return Error::success(); | ||||
5210 | } | ||||
5211 | |||||
5212 | /// Find the function body in the bitcode stream | ||||
5213 | Error BitcodeReader::findFunctionInStream( | ||||
5214 | Function *F, | ||||
5215 | DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { | ||||
5216 | while (DeferredFunctionInfoIterator->second == 0) { | ||||
5217 | // This is the fallback handling for the old format bitcode that | ||||
5218 | // didn't contain the function index in the VST, or when we have | ||||
5219 | // an anonymous function which would not have a VST entry. | ||||
5220 | // Assert that we have one of those two cases. | ||||
5221 | assert(VSTOffset == 0 || !F->hasName())((VSTOffset == 0 || !F->hasName()) ? static_cast<void> (0) : __assert_fail ("VSTOffset == 0 || !F->hasName()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5221, __PRETTY_FUNCTION__)); | ||||
5222 | // Parse the next body in the stream and set its position in the | ||||
5223 | // DeferredFunctionInfo map. | ||||
5224 | if (Error Err = rememberAndSkipFunctionBodies()) | ||||
5225 | return Err; | ||||
5226 | } | ||||
5227 | return Error::success(); | ||||
5228 | } | ||||
5229 | |||||
5230 | SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { | ||||
5231 | if (Val == SyncScope::SingleThread || Val == SyncScope::System) | ||||
5232 | return SyncScope::ID(Val); | ||||
5233 | if (Val >= SSIDs.size()) | ||||
5234 | return SyncScope::System; // Map unknown synchronization scopes to system. | ||||
5235 | return SSIDs[Val]; | ||||
5236 | } | ||||
5237 | |||||
5238 | //===----------------------------------------------------------------------===// | ||||
5239 | // GVMaterializer implementation | ||||
5240 | //===----------------------------------------------------------------------===// | ||||
5241 | |||||
5242 | Error BitcodeReader::materialize(GlobalValue *GV) { | ||||
5243 | Function *F = dyn_cast<Function>(GV); | ||||
5244 | // If it's not a function or is already material, ignore the request. | ||||
5245 | if (!F || !F->isMaterializable()) | ||||
5246 | return Error::success(); | ||||
5247 | |||||
5248 | DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); | ||||
5249 | assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!")((DFII != DeferredFunctionInfo.end() && "Deferred function not found!" ) ? static_cast<void> (0) : __assert_fail ("DFII != DeferredFunctionInfo.end() && \"Deferred function not found!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5249, __PRETTY_FUNCTION__)); | ||||
5250 | // If its position is recorded as 0, its body is somewhere in the stream | ||||
5251 | // but we haven't seen it yet. | ||||
5252 | if (DFII->second == 0) | ||||
5253 | if (Error Err = findFunctionInStream(F, DFII)) | ||||
5254 | return Err; | ||||
5255 | |||||
5256 | // Materialize metadata before parsing any function bodies. | ||||
5257 | if (Error Err = materializeMetadata()) | ||||
5258 | return Err; | ||||
5259 | |||||
5260 | // Move the bit stream to the saved position of the deferred function body. | ||||
5261 | if (Error JumpFailed = Stream.JumpToBit(DFII->second)) | ||||
5262 | return JumpFailed; | ||||
5263 | if (Error Err = parseFunctionBody(F)) | ||||
5264 | return Err; | ||||
5265 | F->setIsMaterializable(false); | ||||
5266 | |||||
5267 | if (StripDebugInfo) | ||||
5268 | stripDebugInfo(*F); | ||||
5269 | |||||
5270 | // Upgrade any old intrinsic calls in the function. | ||||
5271 | for (auto &I : UpgradedIntrinsics) { | ||||
5272 | for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); | ||||
5273 | UI != UE;) { | ||||
5274 | User *U = *UI; | ||||
5275 | ++UI; | ||||
5276 | if (CallInst *CI = dyn_cast<CallInst>(U)) | ||||
5277 | UpgradeIntrinsicCall(CI, I.second); | ||||
5278 | } | ||||
5279 | } | ||||
5280 | |||||
5281 | // Update calls to the remangled intrinsics | ||||
5282 | for (auto &I : RemangledIntrinsics) | ||||
5283 | for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); | ||||
5284 | UI != UE;) | ||||
5285 | // Don't expect any other users than call sites | ||||
5286 | CallSite(*UI++).setCalledFunction(I.second); | ||||
5287 | |||||
5288 | // Finish fn->subprogram upgrade for materialized functions. | ||||
5289 | if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) | ||||
5290 | F->setSubprogram(SP); | ||||
5291 | |||||
5292 | // Check if the TBAA Metadata are valid, otherwise we will need to strip them. | ||||
5293 | if (!MDLoader->isStrippingTBAA()) { | ||||
5294 | for (auto &I : instructions(F)) { | ||||
5295 | MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); | ||||
5296 | if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) | ||||
5297 | continue; | ||||
5298 | MDLoader->setStripTBAA(true); | ||||
5299 | stripTBAA(F->getParent()); | ||||
5300 | } | ||||
5301 | } | ||||
5302 | |||||
5303 | // Bring in any functions that this function forward-referenced via | ||||
5304 | // blockaddresses. | ||||
5305 | return materializeForwardReferencedFunctions(); | ||||
5306 | } | ||||
5307 | |||||
5308 | Error BitcodeReader::materializeModule() { | ||||
5309 | if (Error Err = materializeMetadata()) | ||||
5310 | return Err; | ||||
5311 | |||||
5312 | // Promise to materialize all forward references. | ||||
5313 | WillMaterializeAllForwardRefs = true; | ||||
5314 | |||||
5315 | // Iterate over the module, deserializing any functions that are still on | ||||
5316 | // disk. | ||||
5317 | for (Function &F : *TheModule) { | ||||
5318 | if (Error Err = materialize(&F)) | ||||
5319 | return Err; | ||||
5320 | } | ||||
5321 | // At this point, if there are any function bodies, parse the rest of | ||||
5322 | // the bits in the module past the last function block we have recorded | ||||
5323 | // through either lazy scanning or the VST. | ||||
5324 | if (LastFunctionBlockBit || NextUnreadBit) | ||||
5325 | if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit | ||||
5326 | ? LastFunctionBlockBit | ||||
5327 | : NextUnreadBit)) | ||||
5328 | return Err; | ||||
5329 | |||||
5330 | // Check that all block address forward references got resolved (as we | ||||
5331 | // promised above). | ||||
5332 | if (!BasicBlockFwdRefs.empty()) | ||||
5333 | return error("Never resolved function from blockaddress"); | ||||
5334 | |||||
5335 | // Upgrade any intrinsic calls that slipped through (should not happen!) and | ||||
5336 | // delete the old functions to clean up. We can't do this unless the entire | ||||
5337 | // module is materialized because there could always be another function body | ||||
5338 | // with calls to the old function. | ||||
5339 | for (auto &I : UpgradedIntrinsics) { | ||||
5340 | for (auto *U : I.first->users()) { | ||||
5341 | if (CallInst *CI = dyn_cast<CallInst>(U)) | ||||
5342 | UpgradeIntrinsicCall(CI, I.second); | ||||
5343 | } | ||||
5344 | if (!I.first->use_empty()) | ||||
5345 | I.first->replaceAllUsesWith(I.second); | ||||
5346 | I.first->eraseFromParent(); | ||||
5347 | } | ||||
5348 | UpgradedIntrinsics.clear(); | ||||
5349 | // Do the same for remangled intrinsics | ||||
5350 | for (auto &I : RemangledIntrinsics) { | ||||
5351 | I.first->replaceAllUsesWith(I.second); | ||||
5352 | I.first->eraseFromParent(); | ||||
5353 | } | ||||
5354 | RemangledIntrinsics.clear(); | ||||
5355 | |||||
5356 | UpgradeDebugInfo(*TheModule); | ||||
5357 | |||||
5358 | UpgradeModuleFlags(*TheModule); | ||||
5359 | |||||
5360 | UpgradeARCRuntime(*TheModule); | ||||
5361 | |||||
5362 | return Error::success(); | ||||
5363 | } | ||||
5364 | |||||
5365 | std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { | ||||
5366 | return IdentifiedStructTypes; | ||||
5367 | } | ||||
5368 | |||||
5369 | ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( | ||||
5370 | BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, | ||||
5371 | StringRef ModulePath, unsigned ModuleId) | ||||
5372 | : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), | ||||
5373 | ModulePath(ModulePath), ModuleId(ModuleId) {} | ||||
5374 | |||||
5375 | void ModuleSummaryIndexBitcodeReader::addThisModule() { | ||||
5376 | TheIndex.addModule(ModulePath, ModuleId); | ||||
5377 | } | ||||
5378 | |||||
5379 | ModuleSummaryIndex::ModuleInfo * | ||||
5380 | ModuleSummaryIndexBitcodeReader::getThisModule() { | ||||
5381 | return TheIndex.getModule(ModulePath); | ||||
5382 | } | ||||
5383 | |||||
5384 | std::pair<ValueInfo, GlobalValue::GUID> | ||||
5385 | ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { | ||||
5386 | auto VGI = ValueIdToValueInfoMap[ValueId]; | ||||
5387 | assert(VGI.first)((VGI.first) ? static_cast<void> (0) : __assert_fail ("VGI.first" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5387, __PRETTY_FUNCTION__)); | ||||
5388 | return VGI; | ||||
5389 | } | ||||
5390 | |||||
5391 | void ModuleSummaryIndexBitcodeReader::setValueGUID( | ||||
5392 | uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, | ||||
5393 | StringRef SourceFileName) { | ||||
5394 | std::string GlobalId = | ||||
5395 | GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); | ||||
5396 | auto ValueGUID = GlobalValue::getGUID(GlobalId); | ||||
5397 | auto OriginalNameID = ValueGUID; | ||||
5398 | if (GlobalValue::isLocalLinkage(Linkage)) | ||||
5399 | OriginalNameID = GlobalValue::getGUID(ValueName); | ||||
5400 | if (PrintSummaryGUIDs) | ||||
5401 | dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " | ||||
5402 | << ValueName << "\n"; | ||||
5403 | |||||
5404 | // UseStrtab is false for legacy summary formats and value names are | ||||
5405 | // created on stack. In that case we save the name in a string saver in | ||||
5406 | // the index so that the value name can be recorded. | ||||
5407 | ValueIdToValueInfoMap[ValueID] = std::make_pair( | ||||
5408 | TheIndex.getOrInsertValueInfo( | ||||
5409 | ValueGUID, | ||||
5410 | UseStrtab ? ValueName : TheIndex.saveString(ValueName)), | ||||
5411 | OriginalNameID); | ||||
5412 | } | ||||
5413 | |||||
5414 | // Specialized value symbol table parser used when reading module index | ||||
5415 | // blocks where we don't actually create global values. The parsed information | ||||
5416 | // is saved in the bitcode reader for use when later parsing summaries. | ||||
5417 | Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( | ||||
5418 | uint64_t Offset, | ||||
5419 | DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { | ||||
5420 | // With a strtab the VST is not required to parse the summary. | ||||
5421 | if (UseStrtab) | ||||
5422 | return Error::success(); | ||||
5423 | |||||
5424 | assert(Offset > 0 && "Expected non-zero VST offset")((Offset > 0 && "Expected non-zero VST offset") ? static_cast <void> (0) : __assert_fail ("Offset > 0 && \"Expected non-zero VST offset\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5424, __PRETTY_FUNCTION__)); | ||||
5425 | Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); | ||||
5426 | if (!MaybeCurrentBit) | ||||
5427 | return MaybeCurrentBit.takeError(); | ||||
5428 | uint64_t CurrentBit = MaybeCurrentBit.get(); | ||||
5429 | |||||
5430 | if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) | ||||
5431 | return Err; | ||||
5432 | |||||
5433 | SmallVector<uint64_t, 64> Record; | ||||
5434 | |||||
5435 | // Read all the records for this value table. | ||||
5436 | SmallString<128> ValueName; | ||||
5437 | |||||
5438 | while (true) { | ||||
5439 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
5440 | if (!MaybeEntry) | ||||
5441 | return MaybeEntry.takeError(); | ||||
5442 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
5443 | |||||
5444 | switch (Entry.Kind) { | ||||
5445 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
5446 | case BitstreamEntry::Error: | ||||
5447 | return error("Malformed block"); | ||||
5448 | case BitstreamEntry::EndBlock: | ||||
5449 | // Done parsing VST, jump back to wherever we came from. | ||||
5450 | if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) | ||||
5451 | return JumpFailed; | ||||
5452 | return Error::success(); | ||||
5453 | case BitstreamEntry::Record: | ||||
5454 | // The interesting case. | ||||
5455 | break; | ||||
5456 | } | ||||
5457 | |||||
5458 | // Read a record. | ||||
5459 | Record.clear(); | ||||
5460 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
5461 | if (!MaybeRecord) | ||||
5462 | return MaybeRecord.takeError(); | ||||
5463 | switch (MaybeRecord.get()) { | ||||
5464 | default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). | ||||
5465 | break; | ||||
5466 | case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] | ||||
5467 | if (convertToString(Record, 1, ValueName)) | ||||
5468 | return error("Invalid record"); | ||||
5469 | unsigned ValueID = Record[0]; | ||||
5470 | assert(!SourceFileName.empty())((!SourceFileName.empty()) ? static_cast<void> (0) : __assert_fail ("!SourceFileName.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5470, __PRETTY_FUNCTION__)); | ||||
5471 | auto VLI = ValueIdToLinkageMap.find(ValueID); | ||||
5472 | assert(VLI != ValueIdToLinkageMap.end() &&((VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?" ) ? static_cast<void> (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5473, __PRETTY_FUNCTION__)) | ||||
5473 | "No linkage found for VST entry?")((VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?" ) ? static_cast<void> (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5473, __PRETTY_FUNCTION__)); | ||||
5474 | auto Linkage = VLI->second; | ||||
5475 | setValueGUID(ValueID, ValueName, Linkage, SourceFileName); | ||||
5476 | ValueName.clear(); | ||||
5477 | break; | ||||
5478 | } | ||||
5479 | case bitc::VST_CODE_FNENTRY: { | ||||
5480 | // VST_CODE_FNENTRY: [valueid, offset, namechar x N] | ||||
5481 | if (convertToString(Record, 2, ValueName)) | ||||
5482 | return error("Invalid record"); | ||||
5483 | unsigned ValueID = Record[0]; | ||||
5484 | assert(!SourceFileName.empty())((!SourceFileName.empty()) ? static_cast<void> (0) : __assert_fail ("!SourceFileName.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5484, __PRETTY_FUNCTION__)); | ||||
5485 | auto VLI = ValueIdToLinkageMap.find(ValueID); | ||||
5486 | assert(VLI != ValueIdToLinkageMap.end() &&((VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?" ) ? static_cast<void> (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5487, __PRETTY_FUNCTION__)) | ||||
5487 | "No linkage found for VST entry?")((VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?" ) ? static_cast<void> (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5487, __PRETTY_FUNCTION__)); | ||||
5488 | auto Linkage = VLI->second; | ||||
5489 | setValueGUID(ValueID, ValueName, Linkage, SourceFileName); | ||||
5490 | ValueName.clear(); | ||||
5491 | break; | ||||
5492 | } | ||||
5493 | case bitc::VST_CODE_COMBINED_ENTRY: { | ||||
5494 | // VST_CODE_COMBINED_ENTRY: [valueid, refguid] | ||||
5495 | unsigned ValueID = Record[0]; | ||||
5496 | GlobalValue::GUID RefGUID = Record[1]; | ||||
5497 | // The "original name", which is the second value of the pair will be | ||||
5498 | // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. | ||||
5499 | ValueIdToValueInfoMap[ValueID] = | ||||
5500 | std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); | ||||
5501 | break; | ||||
5502 | } | ||||
5503 | } | ||||
5504 | } | ||||
5505 | } | ||||
5506 | |||||
5507 | // Parse just the blocks needed for building the index out of the module. | ||||
5508 | // At the end of this routine the module Index is populated with a map | ||||
5509 | // from global value id to GlobalValueSummary objects. | ||||
5510 | Error ModuleSummaryIndexBitcodeReader::parseModule() { | ||||
5511 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) | ||||
5512 | return Err; | ||||
5513 | |||||
5514 | SmallVector<uint64_t, 64> Record; | ||||
5515 | DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; | ||||
5516 | unsigned ValueId = 0; | ||||
5517 | |||||
5518 | // Read the index for this module. | ||||
5519 | while (true) { | ||||
5520 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
5521 | if (!MaybeEntry) | ||||
5522 | return MaybeEntry.takeError(); | ||||
5523 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
5524 | |||||
5525 | switch (Entry.Kind) { | ||||
5526 | case BitstreamEntry::Error: | ||||
5527 | return error("Malformed block"); | ||||
5528 | case BitstreamEntry::EndBlock: | ||||
5529 | return Error::success(); | ||||
5530 | |||||
5531 | case BitstreamEntry::SubBlock: | ||||
5532 | switch (Entry.ID) { | ||||
5533 | default: // Skip unknown content. | ||||
5534 | if (Error Err = Stream.SkipBlock()) | ||||
5535 | return Err; | ||||
5536 | break; | ||||
5537 | case bitc::BLOCKINFO_BLOCK_ID: | ||||
5538 | // Need to parse these to get abbrev ids (e.g. for VST) | ||||
5539 | if (readBlockInfo()) | ||||
5540 | return error("Malformed block"); | ||||
5541 | break; | ||||
5542 | case bitc::VALUE_SYMTAB_BLOCK_ID: | ||||
5543 | // Should have been parsed earlier via VSTOffset, unless there | ||||
5544 | // is no summary section. | ||||
5545 | assert(((SeenValueSymbolTable && VSTOffset > 0) ||((((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary ) && "Expected early VST parse via VSTOffset record") ? static_cast<void> (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5547, __PRETTY_FUNCTION__)) | ||||
5546 | !SeenGlobalValSummary) &&((((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary ) && "Expected early VST parse via VSTOffset record") ? static_cast<void> (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5547, __PRETTY_FUNCTION__)) | ||||
5547 | "Expected early VST parse via VSTOffset record")((((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary ) && "Expected early VST parse via VSTOffset record") ? static_cast<void> (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5547, __PRETTY_FUNCTION__)); | ||||
5548 | if (Error Err = Stream.SkipBlock()) | ||||
5549 | return Err; | ||||
5550 | break; | ||||
5551 | case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: | ||||
5552 | case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: | ||||
5553 | // Add the module if it is a per-module index (has a source file name). | ||||
5554 | if (!SourceFileName.empty()) | ||||
5555 | addThisModule(); | ||||
5556 | assert(!SeenValueSymbolTable &&((!SeenValueSymbolTable && "Already read VST when parsing summary block?" ) ? static_cast<void> (0) : __assert_fail ("!SeenValueSymbolTable && \"Already read VST when parsing summary block?\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5557, __PRETTY_FUNCTION__)) | ||||
5557 | "Already read VST when parsing summary block?")((!SeenValueSymbolTable && "Already read VST when parsing summary block?" ) ? static_cast<void> (0) : __assert_fail ("!SeenValueSymbolTable && \"Already read VST when parsing summary block?\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5557, __PRETTY_FUNCTION__)); | ||||
5558 | // We might not have a VST if there were no values in the | ||||
5559 | // summary. An empty summary block generated when we are | ||||
5560 | // performing ThinLTO compiles so we don't later invoke | ||||
5561 | // the regular LTO process on them. | ||||
5562 | if (VSTOffset > 0) { | ||||
5563 | if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) | ||||
5564 | return Err; | ||||
5565 | SeenValueSymbolTable = true; | ||||
5566 | } | ||||
5567 | SeenGlobalValSummary = true; | ||||
5568 | if (Error Err = parseEntireSummary(Entry.ID)) | ||||
5569 | return Err; | ||||
5570 | break; | ||||
5571 | case bitc::MODULE_STRTAB_BLOCK_ID: | ||||
5572 | if (Error Err = parseModuleStringTable()) | ||||
5573 | return Err; | ||||
5574 | break; | ||||
5575 | } | ||||
5576 | continue; | ||||
5577 | |||||
5578 | case BitstreamEntry::Record: { | ||||
5579 | Record.clear(); | ||||
5580 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
5581 | if (!MaybeBitCode) | ||||
5582 | return MaybeBitCode.takeError(); | ||||
5583 | switch (MaybeBitCode.get()) { | ||||
5584 | default: | ||||
5585 | break; // Default behavior, ignore unknown content. | ||||
5586 | case bitc::MODULE_CODE_VERSION: { | ||||
5587 | if (Error Err = parseVersionRecord(Record).takeError()) | ||||
5588 | return Err; | ||||
5589 | break; | ||||
5590 | } | ||||
5591 | /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] | ||||
5592 | case bitc::MODULE_CODE_SOURCE_FILENAME: { | ||||
5593 | SmallString<128> ValueName; | ||||
5594 | if (convertToString(Record, 0, ValueName)) | ||||
5595 | return error("Invalid record"); | ||||
5596 | SourceFileName = ValueName.c_str(); | ||||
5597 | break; | ||||
5598 | } | ||||
5599 | /// MODULE_CODE_HASH: [5*i32] | ||||
5600 | case bitc::MODULE_CODE_HASH: { | ||||
5601 | if (Record.size() != 5) | ||||
5602 | return error("Invalid hash length " + Twine(Record.size()).str()); | ||||
5603 | auto &Hash = getThisModule()->second.second; | ||||
5604 | int Pos = 0; | ||||
5605 | for (auto &Val : Record) { | ||||
5606 | assert(!(Val >> 32) && "Unexpected high bits set")((!(Val >> 32) && "Unexpected high bits set") ? static_cast<void> (0) : __assert_fail ("!(Val >> 32) && \"Unexpected high bits set\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5606, __PRETTY_FUNCTION__)); | ||||
5607 | Hash[Pos++] = Val; | ||||
5608 | } | ||||
5609 | break; | ||||
5610 | } | ||||
5611 | /// MODULE_CODE_VSTOFFSET: [offset] | ||||
5612 | case bitc::MODULE_CODE_VSTOFFSET: | ||||
5613 | if (Record.size() < 1) | ||||
5614 | return error("Invalid record"); | ||||
5615 | // Note that we subtract 1 here because the offset is relative to one | ||||
5616 | // word before the start of the identification or module block, which | ||||
5617 | // was historically always the start of the regular bitcode header. | ||||
5618 | VSTOffset = Record[0] - 1; | ||||
5619 | break; | ||||
5620 | // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] | ||||
5621 | // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] | ||||
5622 | // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] | ||||
5623 | // v2: [strtab offset, strtab size, v1] | ||||
5624 | case bitc::MODULE_CODE_GLOBALVAR: | ||||
5625 | case bitc::MODULE_CODE_FUNCTION: | ||||
5626 | case bitc::MODULE_CODE_ALIAS: { | ||||
5627 | StringRef Name; | ||||
5628 | ArrayRef<uint64_t> GVRecord; | ||||
5629 | std::tie(Name, GVRecord) = readNameFromStrtab(Record); | ||||
5630 | if (GVRecord.size() <= 3) | ||||
5631 | return error("Invalid record"); | ||||
5632 | uint64_t RawLinkage = GVRecord[3]; | ||||
5633 | GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); | ||||
5634 | if (!UseStrtab) { | ||||
5635 | ValueIdToLinkageMap[ValueId++] = Linkage; | ||||
5636 | break; | ||||
5637 | } | ||||
5638 | |||||
5639 | setValueGUID(ValueId++, Name, Linkage, SourceFileName); | ||||
5640 | break; | ||||
5641 | } | ||||
5642 | } | ||||
5643 | } | ||||
5644 | continue; | ||||
5645 | } | ||||
5646 | } | ||||
5647 | } | ||||
5648 | |||||
5649 | std::vector<ValueInfo> | ||||
5650 | ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { | ||||
5651 | std::vector<ValueInfo> Ret; | ||||
5652 | Ret.reserve(Record.size()); | ||||
5653 | for (uint64_t RefValueId : Record) | ||||
5654 | Ret.push_back(getValueInfoFromValueId(RefValueId).first); | ||||
5655 | return Ret; | ||||
5656 | } | ||||
5657 | |||||
5658 | std::vector<FunctionSummary::EdgeTy> | ||||
5659 | ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, | ||||
5660 | bool IsOldProfileFormat, | ||||
5661 | bool HasProfile, bool HasRelBF) { | ||||
5662 | std::vector<FunctionSummary::EdgeTy> Ret; | ||||
5663 | Ret.reserve(Record.size()); | ||||
5664 | for (unsigned I = 0, E = Record.size(); I != E; ++I) { | ||||
5665 | CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; | ||||
5666 | uint64_t RelBF = 0; | ||||
5667 | ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; | ||||
5668 | if (IsOldProfileFormat) { | ||||
5669 | I += 1; // Skip old callsitecount field | ||||
5670 | if (HasProfile) | ||||
5671 | I += 1; // Skip old profilecount field | ||||
5672 | } else if (HasProfile) | ||||
5673 | Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); | ||||
5674 | else if (HasRelBF) | ||||
5675 | RelBF = Record[++I]; | ||||
5676 | Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)}); | ||||
5677 | } | ||||
5678 | return Ret; | ||||
5679 | } | ||||
5680 | |||||
5681 | static void | ||||
5682 | parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, | ||||
5683 | WholeProgramDevirtResolution &Wpd) { | ||||
5684 | uint64_t ArgNum = Record[Slot++]; | ||||
5685 | WholeProgramDevirtResolution::ByArg &B = | ||||
5686 | Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; | ||||
5687 | Slot += ArgNum; | ||||
5688 | |||||
5689 | B.TheKind = | ||||
5690 | static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); | ||||
5691 | B.Info = Record[Slot++]; | ||||
5692 | B.Byte = Record[Slot++]; | ||||
5693 | B.Bit = Record[Slot++]; | ||||
5694 | } | ||||
5695 | |||||
5696 | static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, | ||||
5697 | StringRef Strtab, size_t &Slot, | ||||
5698 | TypeIdSummary &TypeId) { | ||||
5699 | uint64_t Id = Record[Slot++]; | ||||
5700 | WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; | ||||
5701 | |||||
5702 | Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); | ||||
5703 | Wpd.SingleImplName = {Strtab.data() + Record[Slot], | ||||
5704 | static_cast<size_t>(Record[Slot + 1])}; | ||||
5705 | Slot += 2; | ||||
5706 | |||||
5707 | uint64_t ResByArgNum = Record[Slot++]; | ||||
5708 | for (uint64_t I = 0; I != ResByArgNum; ++I) | ||||
5709 | parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); | ||||
5710 | } | ||||
5711 | |||||
5712 | static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, | ||||
5713 | StringRef Strtab, | ||||
5714 | ModuleSummaryIndex &TheIndex) { | ||||
5715 | size_t Slot = 0; | ||||
5716 | TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( | ||||
5717 | {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); | ||||
5718 | Slot += 2; | ||||
5719 | |||||
5720 | TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); | ||||
5721 | TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; | ||||
5722 | TypeId.TTRes.AlignLog2 = Record[Slot++]; | ||||
5723 | TypeId.TTRes.SizeM1 = Record[Slot++]; | ||||
5724 | TypeId.TTRes.BitMask = Record[Slot++]; | ||||
5725 | TypeId.TTRes.InlineBits = Record[Slot++]; | ||||
5726 | |||||
5727 | while (Slot < Record.size()) | ||||
5728 | parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); | ||||
5729 | } | ||||
5730 | |||||
5731 | void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo( | ||||
5732 | ArrayRef<uint64_t> Record, size_t &Slot, | ||||
5733 | TypeIdCompatibleVtableInfo &TypeId) { | ||||
5734 | uint64_t Offset = Record[Slot++]; | ||||
5735 | ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first; | ||||
5736 | TypeId.push_back({Offset, Callee}); | ||||
5737 | } | ||||
5738 | |||||
5739 | void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord( | ||||
5740 | ArrayRef<uint64_t> Record) { | ||||
5741 | size_t Slot = 0; | ||||
5742 | TypeIdCompatibleVtableInfo &TypeId = | ||||
5743 | TheIndex.getOrInsertTypeIdCompatibleVtableSummary( | ||||
5744 | {Strtab.data() + Record[Slot], | ||||
5745 | static_cast<size_t>(Record[Slot + 1])}); | ||||
5746 | Slot += 2; | ||||
5747 | |||||
5748 | while (Slot < Record.size()) | ||||
5749 | parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId); | ||||
5750 | } | ||||
5751 | |||||
5752 | static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt, | ||||
5753 | unsigned WOCnt) { | ||||
5754 | // Readonly and writeonly refs are in the end of the refs list. | ||||
5755 | assert(ROCnt + WOCnt <= Refs.size())((ROCnt + WOCnt <= Refs.size()) ? static_cast<void> ( 0) : __assert_fail ("ROCnt + WOCnt <= Refs.size()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5755, __PRETTY_FUNCTION__)); | ||||
5756 | unsigned FirstWORef = Refs.size() - WOCnt; | ||||
5757 | unsigned RefNo = FirstWORef - ROCnt; | ||||
5758 | for (; RefNo < FirstWORef; ++RefNo) | ||||
5759 | Refs[RefNo].setReadOnly(); | ||||
5760 | for (; RefNo < Refs.size(); ++RefNo) | ||||
5761 | Refs[RefNo].setWriteOnly(); | ||||
5762 | } | ||||
5763 | |||||
5764 | // Eagerly parse the entire summary block. This populates the GlobalValueSummary | ||||
5765 | // objects in the index. | ||||
5766 | Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { | ||||
5767 | if (Error Err = Stream.EnterSubBlock(ID)) | ||||
5768 | return Err; | ||||
5769 | SmallVector<uint64_t, 64> Record; | ||||
5770 | |||||
5771 | // Parse version | ||||
5772 | { | ||||
5773 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
5774 | if (!MaybeEntry) | ||||
5775 | return MaybeEntry.takeError(); | ||||
5776 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
5777 | |||||
5778 | if (Entry.Kind != BitstreamEntry::Record) | ||||
5779 | return error("Invalid Summary Block: record for version expected"); | ||||
5780 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
5781 | if (!MaybeRecord) | ||||
5782 | return MaybeRecord.takeError(); | ||||
5783 | if (MaybeRecord.get() != bitc::FS_VERSION) | ||||
5784 | return error("Invalid Summary Block: version expected"); | ||||
5785 | } | ||||
5786 | const uint64_t Version = Record[0]; | ||||
5787 | const bool IsOldProfileFormat = Version == 1; | ||||
5788 | if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion) | ||||
5789 | return error("Invalid summary version " + Twine(Version) + | ||||
5790 | ". Version should be in the range [1-" + | ||||
5791 | Twine(ModuleSummaryIndex::BitcodeSummaryVersion) + | ||||
5792 | "]."); | ||||
5793 | Record.clear(); | ||||
5794 | |||||
5795 | // Keep around the last seen summary to be used when we see an optional | ||||
5796 | // "OriginalName" attachement. | ||||
5797 | GlobalValueSummary *LastSeenSummary = nullptr; | ||||
5798 | GlobalValue::GUID LastSeenGUID = 0; | ||||
5799 | |||||
5800 | // We can expect to see any number of type ID information records before | ||||
5801 | // each function summary records; these variables store the information | ||||
5802 | // collected so far so that it can be used to create the summary object. | ||||
5803 | std::vector<GlobalValue::GUID> PendingTypeTests; | ||||
5804 | std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, | ||||
5805 | PendingTypeCheckedLoadVCalls; | ||||
5806 | std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, | ||||
5807 | PendingTypeCheckedLoadConstVCalls; | ||||
5808 | |||||
5809 | while (true) { | ||||
5810 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
5811 | if (!MaybeEntry) | ||||
5812 | return MaybeEntry.takeError(); | ||||
5813 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
5814 | |||||
5815 | switch (Entry.Kind) { | ||||
5816 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
5817 | case BitstreamEntry::Error: | ||||
5818 | return error("Malformed block"); | ||||
5819 | case BitstreamEntry::EndBlock: | ||||
5820 | return Error::success(); | ||||
5821 | case BitstreamEntry::Record: | ||||
5822 | // The interesting case. | ||||
5823 | break; | ||||
5824 | } | ||||
5825 | |||||
5826 | // Read a record. The record format depends on whether this | ||||
5827 | // is a per-module index or a combined index file. In the per-module | ||||
5828 | // case the records contain the associated value's ID for correlation | ||||
5829 | // with VST entries. In the combined index the correlation is done | ||||
5830 | // via the bitcode offset of the summary records (which were saved | ||||
5831 | // in the combined index VST entries). The records also contain | ||||
5832 | // information used for ThinLTO renaming and importing. | ||||
5833 | Record.clear(); | ||||
5834 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
5835 | if (!MaybeBitCode) | ||||
5836 | return MaybeBitCode.takeError(); | ||||
5837 | switch (unsigned BitCode = MaybeBitCode.get()) { | ||||
5838 | default: // Default behavior: ignore. | ||||
5839 | break; | ||||
5840 | case bitc::FS_FLAGS: { // [flags] | ||||
5841 | TheIndex.setFlags(Record[0]); | ||||
5842 | break; | ||||
5843 | } | ||||
5844 | case bitc::FS_VALUE_GUID: { // [valueid, refguid] | ||||
5845 | uint64_t ValueID = Record[0]; | ||||
5846 | GlobalValue::GUID RefGUID = Record[1]; | ||||
5847 | ValueIdToValueInfoMap[ValueID] = | ||||
5848 | std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); | ||||
5849 | break; | ||||
5850 | } | ||||
5851 | // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, | ||||
5852 | // numrefs x valueid, n x (valueid)] | ||||
5853 | // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, | ||||
5854 | // numrefs x valueid, | ||||
5855 | // n x (valueid, hotness)] | ||||
5856 | // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, | ||||
5857 | // numrefs x valueid, | ||||
5858 | // n x (valueid, relblockfreq)] | ||||
5859 | case bitc::FS_PERMODULE: | ||||
5860 | case bitc::FS_PERMODULE_RELBF: | ||||
5861 | case bitc::FS_PERMODULE_PROFILE: { | ||||
5862 | unsigned ValueID = Record[0]; | ||||
5863 | uint64_t RawFlags = Record[1]; | ||||
5864 | unsigned InstCount = Record[2]; | ||||
5865 | uint64_t RawFunFlags = 0; | ||||
5866 | unsigned NumRefs = Record[3]; | ||||
5867 | unsigned NumRORefs = 0, NumWORefs = 0; | ||||
5868 | int RefListStartIndex = 4; | ||||
5869 | if (Version >= 4) { | ||||
5870 | RawFunFlags = Record[3]; | ||||
5871 | NumRefs = Record[4]; | ||||
5872 | RefListStartIndex = 5; | ||||
5873 | if (Version >= 5) { | ||||
5874 | NumRORefs = Record[5]; | ||||
5875 | RefListStartIndex = 6; | ||||
5876 | if (Version >= 7) { | ||||
5877 | NumWORefs = Record[6]; | ||||
5878 | RefListStartIndex = 7; | ||||
5879 | } | ||||
5880 | } | ||||
5881 | } | ||||
5882 | |||||
5883 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
5884 | // The module path string ref set in the summary must be owned by the | ||||
5885 | // index's module string table. Since we don't have a module path | ||||
5886 | // string table section in the per-module index, we create a single | ||||
5887 | // module path string table entry with an empty (0) ID to take | ||||
5888 | // ownership. | ||||
5889 | int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; | ||||
5890 | assert(Record.size() >= RefListStartIndex + NumRefs &&((Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? static_cast<void> (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5891, __PRETTY_FUNCTION__)) | ||||
5891 | "Record size inconsistent with number of references")((Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? static_cast<void> (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 5891, __PRETTY_FUNCTION__)); | ||||
5892 | std::vector<ValueInfo> Refs = makeRefList( | ||||
5893 | ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); | ||||
5894 | bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); | ||||
5895 | bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); | ||||
5896 | std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( | ||||
5897 | ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), | ||||
5898 | IsOldProfileFormat, HasProfile, HasRelBF); | ||||
5899 | setSpecialRefs(Refs, NumRORefs, NumWORefs); | ||||
5900 | auto FS = std::make_unique<FunctionSummary>( | ||||
5901 | Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0, | ||||
5902 | std::move(Refs), std::move(Calls), std::move(PendingTypeTests), | ||||
5903 | std::move(PendingTypeTestAssumeVCalls), | ||||
5904 | std::move(PendingTypeCheckedLoadVCalls), | ||||
5905 | std::move(PendingTypeTestAssumeConstVCalls), | ||||
5906 | std::move(PendingTypeCheckedLoadConstVCalls)); | ||||
5907 | auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); | ||||
5908 | FS->setModulePath(getThisModule()->first()); | ||||
5909 | FS->setOriginalName(VIAndOriginalGUID.second); | ||||
5910 | TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS)); | ||||
5911 | break; | ||||
5912 | } | ||||
5913 | // FS_ALIAS: [valueid, flags, valueid] | ||||
5914 | // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as | ||||
5915 | // they expect all aliasee summaries to be available. | ||||
5916 | case bitc::FS_ALIAS: { | ||||
5917 | unsigned ValueID = Record[0]; | ||||
5918 | uint64_t RawFlags = Record[1]; | ||||
5919 | unsigned AliaseeID = Record[2]; | ||||
5920 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
5921 | auto AS = std::make_unique<AliasSummary>(Flags); | ||||
5922 | // The module path string ref set in the summary must be owned by the | ||||
5923 | // index's module string table. Since we don't have a module path | ||||
5924 | // string table section in the per-module index, we create a single | ||||
5925 | // module path string table entry with an empty (0) ID to take | ||||
5926 | // ownership. | ||||
5927 | AS->setModulePath(getThisModule()->first()); | ||||
5928 | |||||
5929 | auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first; | ||||
5930 | auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath); | ||||
5931 | if (!AliaseeInModule) | ||||
5932 | return error("Alias expects aliasee summary to be parsed"); | ||||
5933 | AS->setAliasee(AliaseeVI, AliaseeInModule); | ||||
5934 | |||||
5935 | auto GUID = getValueInfoFromValueId(ValueID); | ||||
5936 | AS->setOriginalName(GUID.second); | ||||
5937 | TheIndex.addGlobalValueSummary(GUID.first, std::move(AS)); | ||||
5938 | break; | ||||
5939 | } | ||||
5940 | // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid] | ||||
5941 | case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { | ||||
5942 | unsigned ValueID = Record[0]; | ||||
5943 | uint64_t RawFlags = Record[1]; | ||||
5944 | unsigned RefArrayStart = 2; | ||||
5945 | GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, | ||||
5946 | /* WriteOnly */ false, | ||||
5947 | /* Constant */ false, | ||||
5948 | GlobalObject::VCallVisibilityPublic); | ||||
5949 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
5950 | if (Version >= 5) { | ||||
5951 | GVF = getDecodedGVarFlags(Record[2]); | ||||
5952 | RefArrayStart = 3; | ||||
5953 | } | ||||
5954 | std::vector<ValueInfo> Refs = | ||||
5955 | makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); | ||||
5956 | auto FS = | ||||
5957 | std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); | ||||
5958 | FS->setModulePath(getThisModule()->first()); | ||||
5959 | auto GUID = getValueInfoFromValueId(ValueID); | ||||
5960 | FS->setOriginalName(GUID.second); | ||||
5961 | TheIndex.addGlobalValueSummary(GUID.first, std::move(FS)); | ||||
5962 | break; | ||||
5963 | } | ||||
5964 | // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, | ||||
5965 | // numrefs, numrefs x valueid, | ||||
5966 | // n x (valueid, offset)] | ||||
5967 | case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: { | ||||
5968 | unsigned ValueID = Record[0]; | ||||
5969 | uint64_t RawFlags = Record[1]; | ||||
5970 | GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]); | ||||
5971 | unsigned NumRefs = Record[3]; | ||||
5972 | unsigned RefListStartIndex = 4; | ||||
5973 | unsigned VTableListStartIndex = RefListStartIndex + NumRefs; | ||||
5974 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
5975 | std::vector<ValueInfo> Refs = makeRefList( | ||||
5976 | ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); | ||||
5977 | VTableFuncList VTableFuncs; | ||||
5978 | for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) { | ||||
5979 | ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; | ||||
5980 | uint64_t Offset = Record[++I]; | ||||
5981 | VTableFuncs.push_back({Callee, Offset}); | ||||
5982 | } | ||||
5983 | auto VS = | ||||
5984 | std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); | ||||
5985 | VS->setModulePath(getThisModule()->first()); | ||||
5986 | VS->setVTableFuncs(VTableFuncs); | ||||
5987 | auto GUID = getValueInfoFromValueId(ValueID); | ||||
5988 | VS->setOriginalName(GUID.second); | ||||
5989 | TheIndex.addGlobalValueSummary(GUID.first, std::move(VS)); | ||||
5990 | break; | ||||
5991 | } | ||||
5992 | // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, | ||||
5993 | // numrefs x valueid, n x (valueid)] | ||||
5994 | // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, | ||||
5995 | // numrefs x valueid, n x (valueid, hotness)] | ||||
5996 | case bitc::FS_COMBINED: | ||||
5997 | case bitc::FS_COMBINED_PROFILE: { | ||||
5998 | unsigned ValueID = Record[0]; | ||||
5999 | uint64_t ModuleId = Record[1]; | ||||
6000 | uint64_t RawFlags = Record[2]; | ||||
6001 | unsigned InstCount = Record[3]; | ||||
6002 | uint64_t RawFunFlags = 0; | ||||
6003 | uint64_t EntryCount = 0; | ||||
6004 | unsigned NumRefs = Record[4]; | ||||
6005 | unsigned NumRORefs = 0, NumWORefs = 0; | ||||
6006 | int RefListStartIndex = 5; | ||||
6007 | |||||
6008 | if (Version >= 4) { | ||||
6009 | RawFunFlags = Record[4]; | ||||
6010 | RefListStartIndex = 6; | ||||
6011 | size_t NumRefsIndex = 5; | ||||
6012 | if (Version >= 5) { | ||||
6013 | unsigned NumRORefsOffset = 1; | ||||
6014 | RefListStartIndex = 7; | ||||
6015 | if (Version >= 6) { | ||||
6016 | NumRefsIndex = 6; | ||||
6017 | EntryCount = Record[5]; | ||||
6018 | RefListStartIndex = 8; | ||||
6019 | if (Version >= 7) { | ||||
6020 | RefListStartIndex = 9; | ||||
6021 | NumWORefs = Record[8]; | ||||
6022 | NumRORefsOffset = 2; | ||||
6023 | } | ||||
6024 | } | ||||
6025 | NumRORefs = Record[RefListStartIndex - NumRORefsOffset]; | ||||
6026 | } | ||||
6027 | NumRefs = Record[NumRefsIndex]; | ||||
6028 | } | ||||
6029 | |||||
6030 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
6031 | int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; | ||||
6032 | assert(Record.size() >= RefListStartIndex + NumRefs &&((Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? static_cast<void> (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6033, __PRETTY_FUNCTION__)) | ||||
6033 | "Record size inconsistent with number of references")((Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? static_cast<void> (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6033, __PRETTY_FUNCTION__)); | ||||
6034 | std::vector<ValueInfo> Refs = makeRefList( | ||||
6035 | ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); | ||||
6036 | bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); | ||||
6037 | std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( | ||||
6038 | ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), | ||||
6039 | IsOldProfileFormat, HasProfile, false); | ||||
6040 | ValueInfo VI = getValueInfoFromValueId(ValueID).first; | ||||
6041 | setSpecialRefs(Refs, NumRORefs, NumWORefs); | ||||
6042 | auto FS = std::make_unique<FunctionSummary>( | ||||
6043 | Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount, | ||||
6044 | std::move(Refs), std::move(Edges), std::move(PendingTypeTests), | ||||
6045 | std::move(PendingTypeTestAssumeVCalls), | ||||
6046 | std::move(PendingTypeCheckedLoadVCalls), | ||||
6047 | std::move(PendingTypeTestAssumeConstVCalls), | ||||
6048 | std::move(PendingTypeCheckedLoadConstVCalls)); | ||||
6049 | LastSeenSummary = FS.get(); | ||||
6050 | LastSeenGUID = VI.getGUID(); | ||||
6051 | FS->setModulePath(ModuleIdMap[ModuleId]); | ||||
6052 | TheIndex.addGlobalValueSummary(VI, std::move(FS)); | ||||
6053 | break; | ||||
6054 | } | ||||
6055 | // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] | ||||
6056 | // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as | ||||
6057 | // they expect all aliasee summaries to be available. | ||||
6058 | case bitc::FS_COMBINED_ALIAS: { | ||||
6059 | unsigned ValueID = Record[0]; | ||||
6060 | uint64_t ModuleId = Record[1]; | ||||
6061 | uint64_t RawFlags = Record[2]; | ||||
6062 | unsigned AliaseeValueId = Record[3]; | ||||
6063 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
6064 | auto AS = std::make_unique<AliasSummary>(Flags); | ||||
6065 | LastSeenSummary = AS.get(); | ||||
6066 | AS->setModulePath(ModuleIdMap[ModuleId]); | ||||
6067 | |||||
6068 | auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first; | ||||
6069 | auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); | ||||
6070 | AS->setAliasee(AliaseeVI, AliaseeInModule); | ||||
6071 | |||||
6072 | ValueInfo VI = getValueInfoFromValueId(ValueID).first; | ||||
6073 | LastSeenGUID = VI.getGUID(); | ||||
6074 | TheIndex.addGlobalValueSummary(VI, std::move(AS)); | ||||
6075 | break; | ||||
6076 | } | ||||
6077 | // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] | ||||
6078 | case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { | ||||
6079 | unsigned ValueID = Record[0]; | ||||
6080 | uint64_t ModuleId = Record[1]; | ||||
6081 | uint64_t RawFlags = Record[2]; | ||||
6082 | unsigned RefArrayStart = 3; | ||||
6083 | GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, | ||||
6084 | /* WriteOnly */ false, | ||||
6085 | /* Constant */ false, | ||||
6086 | GlobalObject::VCallVisibilityPublic); | ||||
6087 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); | ||||
6088 | if (Version >= 5) { | ||||
6089 | GVF = getDecodedGVarFlags(Record[3]); | ||||
6090 | RefArrayStart = 4; | ||||
6091 | } | ||||
6092 | std::vector<ValueInfo> Refs = | ||||
6093 | makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); | ||||
6094 | auto FS = | ||||
6095 | std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); | ||||
6096 | LastSeenSummary = FS.get(); | ||||
6097 | FS->setModulePath(ModuleIdMap[ModuleId]); | ||||
6098 | ValueInfo VI = getValueInfoFromValueId(ValueID).first; | ||||
6099 | LastSeenGUID = VI.getGUID(); | ||||
6100 | TheIndex.addGlobalValueSummary(VI, std::move(FS)); | ||||
6101 | break; | ||||
6102 | } | ||||
6103 | // FS_COMBINED_ORIGINAL_NAME: [original_name] | ||||
6104 | case bitc::FS_COMBINED_ORIGINAL_NAME: { | ||||
6105 | uint64_t OriginalName = Record[0]; | ||||
6106 | if (!LastSeenSummary) | ||||
6107 | return error("Name attachment that does not follow a combined record"); | ||||
6108 | LastSeenSummary->setOriginalName(OriginalName); | ||||
6109 | TheIndex.addOriginalName(LastSeenGUID, OriginalName); | ||||
6110 | // Reset the LastSeenSummary | ||||
6111 | LastSeenSummary = nullptr; | ||||
6112 | LastSeenGUID = 0; | ||||
6113 | break; | ||||
6114 | } | ||||
6115 | case bitc::FS_TYPE_TESTS: | ||||
6116 | assert(PendingTypeTests.empty())((PendingTypeTests.empty()) ? static_cast<void> (0) : __assert_fail ("PendingTypeTests.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6116, __PRETTY_FUNCTION__)); | ||||
6117 | PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(), | ||||
6118 | Record.end()); | ||||
6119 | break; | ||||
6120 | |||||
6121 | case bitc::FS_TYPE_TEST_ASSUME_VCALLS: | ||||
6122 | assert(PendingTypeTestAssumeVCalls.empty())((PendingTypeTestAssumeVCalls.empty()) ? static_cast<void> (0) : __assert_fail ("PendingTypeTestAssumeVCalls.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6122, __PRETTY_FUNCTION__)); | ||||
6123 | for (unsigned I = 0; I != Record.size(); I += 2) | ||||
6124 | PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); | ||||
6125 | break; | ||||
6126 | |||||
6127 | case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: | ||||
6128 | assert(PendingTypeCheckedLoadVCalls.empty())((PendingTypeCheckedLoadVCalls.empty()) ? static_cast<void > (0) : __assert_fail ("PendingTypeCheckedLoadVCalls.empty()" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6128, __PRETTY_FUNCTION__)); | ||||
6129 | for (unsigned I = 0; I != Record.size(); I += 2) | ||||
6130 | PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); | ||||
6131 | break; | ||||
6132 | |||||
6133 | case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: | ||||
6134 | PendingTypeTestAssumeConstVCalls.push_back( | ||||
6135 | {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); | ||||
6136 | break; | ||||
6137 | |||||
6138 | case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: | ||||
6139 | PendingTypeCheckedLoadConstVCalls.push_back( | ||||
6140 | {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); | ||||
6141 | break; | ||||
6142 | |||||
6143 | case bitc::FS_CFI_FUNCTION_DEFS: { | ||||
6144 | std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); | ||||
6145 | for (unsigned I = 0; I != Record.size(); I += 2) | ||||
6146 | CfiFunctionDefs.insert( | ||||
6147 | {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); | ||||
6148 | break; | ||||
6149 | } | ||||
6150 | |||||
6151 | case bitc::FS_CFI_FUNCTION_DECLS: { | ||||
6152 | std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); | ||||
6153 | for (unsigned I = 0; I != Record.size(); I += 2) | ||||
6154 | CfiFunctionDecls.insert( | ||||
6155 | {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); | ||||
6156 | break; | ||||
6157 | } | ||||
6158 | |||||
6159 | case bitc::FS_TYPE_ID: | ||||
6160 | parseTypeIdSummaryRecord(Record, Strtab, TheIndex); | ||||
6161 | break; | ||||
6162 | |||||
6163 | case bitc::FS_TYPE_ID_METADATA: | ||||
6164 | parseTypeIdCompatibleVtableSummaryRecord(Record); | ||||
6165 | break; | ||||
6166 | } | ||||
6167 | } | ||||
6168 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6168); | ||||
6169 | } | ||||
6170 | |||||
6171 | // Parse the module string table block into the Index. | ||||
6172 | // This populates the ModulePathStringTable map in the index. | ||||
6173 | Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { | ||||
6174 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) | ||||
6175 | return Err; | ||||
6176 | |||||
6177 | SmallVector<uint64_t, 64> Record; | ||||
6178 | |||||
6179 | SmallString<128> ModulePath; | ||||
6180 | ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; | ||||
6181 | |||||
6182 | while (true) { | ||||
6183 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
6184 | if (!MaybeEntry) | ||||
6185 | return MaybeEntry.takeError(); | ||||
6186 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
6187 | |||||
6188 | switch (Entry.Kind) { | ||||
6189 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
6190 | case BitstreamEntry::Error: | ||||
6191 | return error("Malformed block"); | ||||
6192 | case BitstreamEntry::EndBlock: | ||||
6193 | return Error::success(); | ||||
6194 | case BitstreamEntry::Record: | ||||
6195 | // The interesting case. | ||||
6196 | break; | ||||
6197 | } | ||||
6198 | |||||
6199 | Record.clear(); | ||||
6200 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); | ||||
6201 | if (!MaybeRecord) | ||||
6202 | return MaybeRecord.takeError(); | ||||
6203 | switch (MaybeRecord.get()) { | ||||
6204 | default: // Default behavior: ignore. | ||||
6205 | break; | ||||
6206 | case bitc::MST_CODE_ENTRY: { | ||||
6207 | // MST_ENTRY: [modid, namechar x N] | ||||
6208 | uint64_t ModuleId = Record[0]; | ||||
6209 | |||||
6210 | if (convertToString(Record, 1, ModulePath)) | ||||
6211 | return error("Invalid record"); | ||||
6212 | |||||
6213 | LastSeenModule = TheIndex.addModule(ModulePath, ModuleId); | ||||
6214 | ModuleIdMap[ModuleId] = LastSeenModule->first(); | ||||
6215 | |||||
6216 | ModulePath.clear(); | ||||
6217 | break; | ||||
6218 | } | ||||
6219 | /// MST_CODE_HASH: [5*i32] | ||||
6220 | case bitc::MST_CODE_HASH: { | ||||
6221 | if (Record.size() != 5) | ||||
6222 | return error("Invalid hash length " + Twine(Record.size()).str()); | ||||
6223 | if (!LastSeenModule) | ||||
6224 | return error("Invalid hash that does not follow a module path"); | ||||
6225 | int Pos = 0; | ||||
6226 | for (auto &Val : Record) { | ||||
6227 | assert(!(Val >> 32) && "Unexpected high bits set")((!(Val >> 32) && "Unexpected high bits set") ? static_cast<void> (0) : __assert_fail ("!(Val >> 32) && \"Unexpected high bits set\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6227, __PRETTY_FUNCTION__)); | ||||
6228 | LastSeenModule->second.second[Pos++] = Val; | ||||
6229 | } | ||||
6230 | // Reset LastSeenModule to avoid overriding the hash unexpectedly. | ||||
6231 | LastSeenModule = nullptr; | ||||
6232 | break; | ||||
6233 | } | ||||
6234 | } | ||||
6235 | } | ||||
6236 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6236); | ||||
6237 | } | ||||
6238 | |||||
6239 | namespace { | ||||
6240 | |||||
6241 | // FIXME: This class is only here to support the transition to llvm::Error. It | ||||
6242 | // will be removed once this transition is complete. Clients should prefer to | ||||
6243 | // deal with the Error value directly, rather than converting to error_code. | ||||
6244 | class BitcodeErrorCategoryType : public std::error_category { | ||||
6245 | const char *name() const noexcept override { | ||||
6246 | return "llvm.bitcode"; | ||||
6247 | } | ||||
6248 | |||||
6249 | std::string message(int IE) const override { | ||||
6250 | BitcodeError E = static_cast<BitcodeError>(IE); | ||||
6251 | switch (E) { | ||||
6252 | case BitcodeError::CorruptedBitcode: | ||||
6253 | return "Corrupted bitcode"; | ||||
6254 | } | ||||
6255 | llvm_unreachable("Unknown error type!")::llvm::llvm_unreachable_internal("Unknown error type!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6255); | ||||
6256 | } | ||||
6257 | }; | ||||
6258 | |||||
6259 | } // end anonymous namespace | ||||
6260 | |||||
6261 | static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; | ||||
6262 | |||||
6263 | const std::error_category &llvm::BitcodeErrorCategory() { | ||||
6264 | return *ErrorCategory; | ||||
6265 | } | ||||
6266 | |||||
6267 | static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, | ||||
6268 | unsigned Block, unsigned RecordID) { | ||||
6269 | if (Error Err = Stream.EnterSubBlock(Block)) | ||||
6270 | return std::move(Err); | ||||
6271 | |||||
6272 | StringRef Strtab; | ||||
6273 | while (true) { | ||||
6274 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
6275 | if (!MaybeEntry) | ||||
6276 | return MaybeEntry.takeError(); | ||||
6277 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
6278 | |||||
6279 | switch (Entry.Kind) { | ||||
6280 | case BitstreamEntry::EndBlock: | ||||
6281 | return Strtab; | ||||
6282 | |||||
6283 | case BitstreamEntry::Error: | ||||
6284 | return error("Malformed block"); | ||||
6285 | |||||
6286 | case BitstreamEntry::SubBlock: | ||||
6287 | if (Error Err = Stream.SkipBlock()) | ||||
6288 | return std::move(Err); | ||||
6289 | break; | ||||
6290 | |||||
6291 | case BitstreamEntry::Record: | ||||
6292 | StringRef Blob; | ||||
6293 | SmallVector<uint64_t, 1> Record; | ||||
6294 | Expected<unsigned> MaybeRecord = | ||||
6295 | Stream.readRecord(Entry.ID, Record, &Blob); | ||||
6296 | if (!MaybeRecord) | ||||
6297 | return MaybeRecord.takeError(); | ||||
6298 | if (MaybeRecord.get() == RecordID) | ||||
6299 | Strtab = Blob; | ||||
6300 | break; | ||||
6301 | } | ||||
6302 | } | ||||
6303 | } | ||||
6304 | |||||
6305 | //===----------------------------------------------------------------------===// | ||||
6306 | // External interface | ||||
6307 | //===----------------------------------------------------------------------===// | ||||
6308 | |||||
6309 | Expected<std::vector<BitcodeModule>> | ||||
6310 | llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { | ||||
6311 | auto FOrErr = getBitcodeFileContents(Buffer); | ||||
6312 | if (!FOrErr) | ||||
6313 | return FOrErr.takeError(); | ||||
6314 | return std::move(FOrErr->Mods); | ||||
6315 | } | ||||
6316 | |||||
6317 | Expected<BitcodeFileContents> | ||||
6318 | llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { | ||||
6319 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); | ||||
6320 | if (!StreamOrErr) | ||||
6321 | return StreamOrErr.takeError(); | ||||
6322 | BitstreamCursor &Stream = *StreamOrErr; | ||||
6323 | |||||
6324 | BitcodeFileContents F; | ||||
6325 | while (true) { | ||||
6326 | uint64_t BCBegin = Stream.getCurrentByteNo(); | ||||
6327 | |||||
6328 | // We may be consuming bitcode from a client that leaves garbage at the end | ||||
6329 | // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to | ||||
6330 | // the end that there cannot possibly be another module, stop looking. | ||||
6331 | if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) | ||||
6332 | return F; | ||||
6333 | |||||
6334 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
6335 | if (!MaybeEntry) | ||||
6336 | return MaybeEntry.takeError(); | ||||
6337 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
6338 | |||||
6339 | switch (Entry.Kind) { | ||||
6340 | case BitstreamEntry::EndBlock: | ||||
6341 | case BitstreamEntry::Error: | ||||
6342 | return error("Malformed block"); | ||||
6343 | |||||
6344 | case BitstreamEntry::SubBlock: { | ||||
6345 | uint64_t IdentificationBit = -1ull; | ||||
6346 | if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { | ||||
6347 | IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; | ||||
6348 | if (Error Err = Stream.SkipBlock()) | ||||
6349 | return std::move(Err); | ||||
6350 | |||||
6351 | { | ||||
6352 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
6353 | if (!MaybeEntry) | ||||
6354 | return MaybeEntry.takeError(); | ||||
6355 | Entry = MaybeEntry.get(); | ||||
6356 | } | ||||
6357 | |||||
6358 | if (Entry.Kind != BitstreamEntry::SubBlock || | ||||
6359 | Entry.ID != bitc::MODULE_BLOCK_ID) | ||||
6360 | return error("Malformed block"); | ||||
6361 | } | ||||
6362 | |||||
6363 | if (Entry.ID == bitc::MODULE_BLOCK_ID) { | ||||
6364 | uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; | ||||
6365 | if (Error Err = Stream.SkipBlock()) | ||||
6366 | return std::move(Err); | ||||
6367 | |||||
6368 | F.Mods.push_back({Stream.getBitcodeBytes().slice( | ||||
6369 | BCBegin, Stream.getCurrentByteNo() - BCBegin), | ||||
6370 | Buffer.getBufferIdentifier(), IdentificationBit, | ||||
6371 | ModuleBit}); | ||||
6372 | continue; | ||||
6373 | } | ||||
6374 | |||||
6375 | if (Entry.ID == bitc::STRTAB_BLOCK_ID) { | ||||
6376 | Expected<StringRef> Strtab = | ||||
6377 | readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); | ||||
6378 | if (!Strtab) | ||||
6379 | return Strtab.takeError(); | ||||
6380 | // This string table is used by every preceding bitcode module that does | ||||
6381 | // not have its own string table. A bitcode file may have multiple | ||||
6382 | // string tables if it was created by binary concatenation, for example | ||||
6383 | // with "llvm-cat -b". | ||||
6384 | for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) { | ||||
6385 | if (!I->Strtab.empty()) | ||||
6386 | break; | ||||
6387 | I->Strtab = *Strtab; | ||||
6388 | } | ||||
6389 | // Similarly, the string table is used by every preceding symbol table; | ||||
6390 | // normally there will be just one unless the bitcode file was created | ||||
6391 | // by binary concatenation. | ||||
6392 | if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) | ||||
6393 | F.StrtabForSymtab = *Strtab; | ||||
6394 | continue; | ||||
6395 | } | ||||
6396 | |||||
6397 | if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { | ||||
6398 | Expected<StringRef> SymtabOrErr = | ||||
6399 | readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); | ||||
6400 | if (!SymtabOrErr) | ||||
6401 | return SymtabOrErr.takeError(); | ||||
6402 | |||||
6403 | // We can expect the bitcode file to have multiple symbol tables if it | ||||
6404 | // was created by binary concatenation. In that case we silently | ||||
6405 | // ignore any subsequent symbol tables, which is fine because this is a | ||||
6406 | // low level function. The client is expected to notice that the number | ||||
6407 | // of modules in the symbol table does not match the number of modules | ||||
6408 | // in the input file and regenerate the symbol table. | ||||
6409 | if (F.Symtab.empty()) | ||||
6410 | F.Symtab = *SymtabOrErr; | ||||
6411 | continue; | ||||
6412 | } | ||||
6413 | |||||
6414 | if (Error Err = Stream.SkipBlock()) | ||||
6415 | return std::move(Err); | ||||
6416 | continue; | ||||
6417 | } | ||||
6418 | case BitstreamEntry::Record: | ||||
6419 | if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) | ||||
6420 | continue; | ||||
6421 | else | ||||
6422 | return StreamFailed.takeError(); | ||||
6423 | } | ||||
6424 | } | ||||
6425 | } | ||||
6426 | |||||
6427 | /// Get a lazy one-at-time loading module from bitcode. | ||||
6428 | /// | ||||
6429 | /// This isn't always used in a lazy context. In particular, it's also used by | ||||
6430 | /// \a parseModule(). If this is truly lazy, then we need to eagerly pull | ||||
6431 | /// in forward-referenced functions from block address references. | ||||
6432 | /// | ||||
6433 | /// \param[in] MaterializeAll Set to \c true if we should materialize | ||||
6434 | /// everything. | ||||
6435 | Expected<std::unique_ptr<Module>> | ||||
6436 | BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, | ||||
6437 | bool ShouldLazyLoadMetadata, bool IsImporting) { | ||||
6438 | BitstreamCursor Stream(Buffer); | ||||
6439 | |||||
6440 | std::string ProducerIdentification; | ||||
6441 | if (IdentificationBit != -1ull) { | ||||
6442 | if (Error JumpFailed = Stream.JumpToBit(IdentificationBit)) | ||||
6443 | return std::move(JumpFailed); | ||||
6444 | Expected<std::string> ProducerIdentificationOrErr = | ||||
6445 | readIdentificationBlock(Stream); | ||||
6446 | if (!ProducerIdentificationOrErr) | ||||
6447 | return ProducerIdentificationOrErr.takeError(); | ||||
6448 | |||||
6449 | ProducerIdentification = *ProducerIdentificationOrErr; | ||||
6450 | } | ||||
6451 | |||||
6452 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) | ||||
6453 | return std::move(JumpFailed); | ||||
6454 | auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, | ||||
6455 | Context); | ||||
6456 | |||||
6457 | std::unique_ptr<Module> M = | ||||
6458 | std::make_unique<Module>(ModuleIdentifier, Context); | ||||
6459 | M->setMaterializer(R); | ||||
6460 | |||||
6461 | // Delay parsing Metadata if ShouldLazyLoadMetadata is true. | ||||
6462 | if (Error Err = | ||||
6463 | R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting)) | ||||
6464 | return std::move(Err); | ||||
6465 | |||||
6466 | if (MaterializeAll) { | ||||
6467 | // Read in the entire module, and destroy the BitcodeReader. | ||||
6468 | if (Error Err = M->materializeAll()) | ||||
6469 | return std::move(Err); | ||||
6470 | } else { | ||||
6471 | // Resolve forward references from blockaddresses. | ||||
6472 | if (Error Err = R->materializeForwardReferencedFunctions()) | ||||
6473 | return std::move(Err); | ||||
6474 | } | ||||
6475 | return std::move(M); | ||||
6476 | } | ||||
6477 | |||||
6478 | Expected<std::unique_ptr<Module>> | ||||
6479 | BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, | ||||
6480 | bool IsImporting) { | ||||
6481 | return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting); | ||||
6482 | } | ||||
6483 | |||||
6484 | // Parse the specified bitcode buffer and merge the index into CombinedIndex. | ||||
6485 | // We don't use ModuleIdentifier here because the client may need to control the | ||||
6486 | // module path used in the combined summary (e.g. when reading summaries for | ||||
6487 | // regular LTO modules). | ||||
6488 | Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex, | ||||
6489 | StringRef ModulePath, uint64_t ModuleId) { | ||||
6490 | BitstreamCursor Stream(Buffer); | ||||
6491 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) | ||||
6492 | return JumpFailed; | ||||
6493 | |||||
6494 | ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, | ||||
6495 | ModulePath, ModuleId); | ||||
6496 | return R.parseModule(); | ||||
6497 | } | ||||
6498 | |||||
6499 | // Parse the specified bitcode buffer, returning the function info index. | ||||
6500 | Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { | ||||
6501 | BitstreamCursor Stream(Buffer); | ||||
6502 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) | ||||
6503 | return std::move(JumpFailed); | ||||
6504 | |||||
6505 | auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); | ||||
6506 | ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, | ||||
6507 | ModuleIdentifier, 0); | ||||
6508 | |||||
6509 | if (Error Err = R.parseModule()) | ||||
6510 | return std::move(Err); | ||||
6511 | |||||
6512 | return std::move(Index); | ||||
6513 | } | ||||
6514 | |||||
6515 | static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream, | ||||
6516 | unsigned ID) { | ||||
6517 | if (Error Err = Stream.EnterSubBlock(ID)) | ||||
6518 | return std::move(Err); | ||||
6519 | SmallVector<uint64_t, 64> Record; | ||||
6520 | |||||
6521 | while (true) { | ||||
6522 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); | ||||
6523 | if (!MaybeEntry) | ||||
6524 | return MaybeEntry.takeError(); | ||||
6525 | BitstreamEntry Entry = MaybeEntry.get(); | ||||
6526 | |||||
6527 | switch (Entry.Kind) { | ||||
6528 | case BitstreamEntry::SubBlock: // Handled for us already. | ||||
6529 | case BitstreamEntry::Error: | ||||
6530 | return error("Malformed block"); | ||||
6531 | case BitstreamEntry::EndBlock: | ||||
6532 | // If no flags record found, conservatively return true to mimic | ||||
6533 | // behavior before this flag was added. | ||||
6534 | return true; | ||||
6535 | case BitstreamEntry::Record: | ||||
6536 | // The interesting case. | ||||
6537 | break; | ||||
6538 | } | ||||
6539 | |||||
6540 | // Look for the FS_FLAGS record. | ||||
6541 | Record.clear(); | ||||
6542 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); | ||||
6543 | if (!MaybeBitCode) | ||||
6544 | return MaybeBitCode.takeError(); | ||||
6545 | switch (MaybeBitCode.get()) { | ||||
6546 | default: // Default behavior: ignore. | ||||
6547 | break; | ||||
6548 | case bitc::FS_FLAGS: { // [flags] | ||||
6549 | uint64_t Flags = Record[0]; | ||||
6550 | // Scan flags. | ||||
6551 | assert(Flags <= 0x3f && "Unexpected bits in flag")((Flags <= 0x3f && "Unexpected bits in flag") ? static_cast <void> (0) : __assert_fail ("Flags <= 0x3f && \"Unexpected bits in flag\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6551, __PRETTY_FUNCTION__)); | ||||
6552 | |||||
6553 | return Flags & 0x8; | ||||
6554 | } | ||||
6555 | } | ||||
6556 | } | ||||
6557 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6557); | ||||
6558 | } | ||||
6559 | |||||
6560 | // Check if the given bitcode buffer contains a global value summary block. | ||||
6561 | Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { | ||||
6562 | BitstreamCursor Stream(Buffer); | ||||
6563 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) | ||||
6564 | return std::move(JumpFailed); | ||||
6565 | |||||
6566 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) | ||||
6567 | return std::move(Err); | ||||
6568 | |||||
6569 | while (true) { | ||||
6570 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); | ||||
6571 | if (!MaybeEntry) | ||||
6572 | return MaybeEntry.takeError(); | ||||
6573 | llvm::BitstreamEntry Entry = MaybeEntry.get(); | ||||
6574 | |||||
6575 | switch (Entry.Kind) { | ||||
6576 | case BitstreamEntry::Error: | ||||
6577 | return error("Malformed block"); | ||||
6578 | case BitstreamEntry::EndBlock: | ||||
6579 | return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false, | ||||
6580 | /*EnableSplitLTOUnit=*/false}; | ||||
6581 | |||||
6582 | case BitstreamEntry::SubBlock: | ||||
6583 | if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { | ||||
6584 | Expected<bool> EnableSplitLTOUnit = | ||||
6585 | getEnableSplitLTOUnitFlag(Stream, Entry.ID); | ||||
6586 | if (!EnableSplitLTOUnit) | ||||
6587 | return EnableSplitLTOUnit.takeError(); | ||||
6588 | return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true, | ||||
6589 | *EnableSplitLTOUnit}; | ||||
6590 | } | ||||
6591 | |||||
6592 | if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) { | ||||
6593 | Expected<bool> EnableSplitLTOUnit = | ||||
6594 | getEnableSplitLTOUnitFlag(Stream, Entry.ID); | ||||
6595 | if (!EnableSplitLTOUnit) | ||||
6596 | return EnableSplitLTOUnit.takeError(); | ||||
6597 | return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true, | ||||
6598 | *EnableSplitLTOUnit}; | ||||
6599 | } | ||||
6600 | |||||
6601 | // Ignore other sub-blocks. | ||||
6602 | if (Error Err = Stream.SkipBlock()) | ||||
6603 | return std::move(Err); | ||||
6604 | continue; | ||||
6605 | |||||
6606 | case BitstreamEntry::Record: | ||||
6607 | if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) | ||||
6608 | continue; | ||||
6609 | else | ||||
6610 | return StreamFailed.takeError(); | ||||
6611 | } | ||||
6612 | } | ||||
6613 | } | ||||
6614 | |||||
6615 | static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { | ||||
6616 | Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); | ||||
6617 | if (!MsOrErr) | ||||
6618 | return MsOrErr.takeError(); | ||||
6619 | |||||
6620 | if (MsOrErr->size() != 1) | ||||
6621 | return error("Expected a single module"); | ||||
6622 | |||||
6623 | return (*MsOrErr)[0]; | ||||
6624 | } | ||||
6625 | |||||
6626 | Expected<std::unique_ptr<Module>> | ||||
6627 | llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, | ||||
6628 | bool ShouldLazyLoadMetadata, bool IsImporting) { | ||||
6629 | Expected<BitcodeModule> BM = getSingleModule(Buffer); | ||||
6630 | if (!BM) | ||||
6631 | return BM.takeError(); | ||||
6632 | |||||
6633 | return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting); | ||||
6634 | } | ||||
6635 | |||||
6636 | Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( | ||||
6637 | std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, | ||||
6638 | bool ShouldLazyLoadMetadata, bool IsImporting) { | ||||
6639 | auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, | ||||
6640 | IsImporting); | ||||
6641 | if (MOrErr) | ||||
6642 | (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); | ||||
6643 | return MOrErr; | ||||
6644 | } | ||||
6645 | |||||
6646 | Expected<std::unique_ptr<Module>> | ||||
6647 | BitcodeModule::parseModule(LLVMContext &Context) { | ||||
6648 | return getModuleImpl(Context, true, false, false); | ||||
6649 | // TODO: Restore the use-lists to the in-memory state when the bitcode was | ||||
6650 | // written. We must defer until the Module has been fully materialized. | ||||
6651 | } | ||||
6652 | |||||
6653 | Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, | ||||
6654 | LLVMContext &Context) { | ||||
6655 | Expected<BitcodeModule> BM = getSingleModule(Buffer); | ||||
6656 | if (!BM) | ||||
6657 | return BM.takeError(); | ||||
6658 | |||||
6659 | return BM->parseModule(Context); | ||||
6660 | } | ||||
6661 | |||||
6662 | Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { | ||||
6663 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); | ||||
6664 | if (!StreamOrErr) | ||||
6665 | return StreamOrErr.takeError(); | ||||
6666 | |||||
6667 | return readTriple(*StreamOrErr); | ||||
6668 | } | ||||
6669 | |||||
6670 | Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { | ||||
6671 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); | ||||
6672 | if (!StreamOrErr) | ||||
6673 | return StreamOrErr.takeError(); | ||||
6674 | |||||
6675 | return hasObjCCategory(*StreamOrErr); | ||||
6676 | } | ||||
6677 | |||||
6678 | Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { | ||||
6679 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); | ||||
6680 | if (!StreamOrErr) | ||||
6681 | return StreamOrErr.takeError(); | ||||
6682 | |||||
6683 | return readIdentificationCode(*StreamOrErr); | ||||
6684 | } | ||||
6685 | |||||
6686 | Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, | ||||
6687 | ModuleSummaryIndex &CombinedIndex, | ||||
6688 | uint64_t ModuleId) { | ||||
6689 | Expected<BitcodeModule> BM = getSingleModule(Buffer); | ||||
6690 | if (!BM) | ||||
6691 | return BM.takeError(); | ||||
6692 | |||||
6693 | return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId); | ||||
6694 | } | ||||
6695 | |||||
6696 | Expected<std::unique_ptr<ModuleSummaryIndex>> | ||||
6697 | llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { | ||||
6698 | Expected<BitcodeModule> BM = getSingleModule(Buffer); | ||||
6699 | if (!BM) | ||||
6700 | return BM.takeError(); | ||||
6701 | |||||
6702 | return BM->getSummary(); | ||||
6703 | } | ||||
6704 | |||||
6705 | Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { | ||||
6706 | Expected<BitcodeModule> BM = getSingleModule(Buffer); | ||||
6707 | if (!BM) | ||||
6708 | return BM.takeError(); | ||||
6709 | |||||
6710 | return BM->getLTOInfo(); | ||||
6711 | } | ||||
6712 | |||||
6713 | Expected<std::unique_ptr<ModuleSummaryIndex>> | ||||
6714 | llvm::getModuleSummaryIndexForFile(StringRef Path, | ||||
6715 | bool IgnoreEmptyThinLTOIndexFile) { | ||||
6716 | ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = | ||||
6717 | MemoryBuffer::getFileOrSTDIN(Path); | ||||
6718 | if (!FileOrErr) | ||||
6719 | return errorCodeToError(FileOrErr.getError()); | ||||
6720 | if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) | ||||
6721 | return nullptr; | ||||
6722 | return getModuleSummaryIndex(**FileOrErr); | ||||
6723 | } |
1 | //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// |
2 | // |
3 | // 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 |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines an API used to report recoverable errors. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_SUPPORT_ERROR_H |
14 | #define LLVM_SUPPORT_ERROR_H |
15 | |
16 | #include "llvm-c/Error.h" |
17 | #include "llvm/ADT/STLExtras.h" |
18 | #include "llvm/ADT/SmallVector.h" |
19 | #include "llvm/ADT/StringExtras.h" |
20 | #include "llvm/ADT/Twine.h" |
21 | #include "llvm/Config/abi-breaking.h" |
22 | #include "llvm/Support/AlignOf.h" |
23 | #include "llvm/Support/Compiler.h" |
24 | #include "llvm/Support/Debug.h" |
25 | #include "llvm/Support/ErrorHandling.h" |
26 | #include "llvm/Support/ErrorOr.h" |
27 | #include "llvm/Support/Format.h" |
28 | #include "llvm/Support/raw_ostream.h" |
29 | #include <algorithm> |
30 | #include <cassert> |
31 | #include <cstdint> |
32 | #include <cstdlib> |
33 | #include <functional> |
34 | #include <memory> |
35 | #include <new> |
36 | #include <string> |
37 | #include <system_error> |
38 | #include <type_traits> |
39 | #include <utility> |
40 | #include <vector> |
41 | |
42 | namespace llvm { |
43 | |
44 | class ErrorSuccess; |
45 | |
46 | /// Base class for error info classes. Do not extend this directly: Extend |
47 | /// the ErrorInfo template subclass instead. |
48 | class ErrorInfoBase { |
49 | public: |
50 | virtual ~ErrorInfoBase() = default; |
51 | |
52 | /// Print an error message to an output stream. |
53 | virtual void log(raw_ostream &OS) const = 0; |
54 | |
55 | /// Return the error message as a string. |
56 | virtual std::string message() const { |
57 | std::string Msg; |
58 | raw_string_ostream OS(Msg); |
59 | log(OS); |
60 | return OS.str(); |
61 | } |
62 | |
63 | /// Convert this error to a std::error_code. |
64 | /// |
65 | /// This is a temporary crutch to enable interaction with code still |
66 | /// using std::error_code. It will be removed in the future. |
67 | virtual std::error_code convertToErrorCode() const = 0; |
68 | |
69 | // Returns the class ID for this type. |
70 | static const void *classID() { return &ID; } |
71 | |
72 | // Returns the class ID for the dynamic type of this ErrorInfoBase instance. |
73 | virtual const void *dynamicClassID() const = 0; |
74 | |
75 | // Check whether this instance is a subclass of the class identified by |
76 | // ClassID. |
77 | virtual bool isA(const void *const ClassID) const { |
78 | return ClassID == classID(); |
79 | } |
80 | |
81 | // Check whether this instance is a subclass of ErrorInfoT. |
82 | template <typename ErrorInfoT> bool isA() const { |
83 | return isA(ErrorInfoT::classID()); |
84 | } |
85 | |
86 | private: |
87 | virtual void anchor(); |
88 | |
89 | static char ID; |
90 | }; |
91 | |
92 | /// Lightweight error class with error context and mandatory checking. |
93 | /// |
94 | /// Instances of this class wrap a ErrorInfoBase pointer. Failure states |
95 | /// are represented by setting the pointer to a ErrorInfoBase subclass |
96 | /// instance containing information describing the failure. Success is |
97 | /// represented by a null pointer value. |
98 | /// |
99 | /// Instances of Error also contains a 'Checked' flag, which must be set |
100 | /// before the destructor is called, otherwise the destructor will trigger a |
101 | /// runtime error. This enforces at runtime the requirement that all Error |
102 | /// instances be checked or returned to the caller. |
103 | /// |
104 | /// There are two ways to set the checked flag, depending on what state the |
105 | /// Error instance is in. For Error instances indicating success, it |
106 | /// is sufficient to invoke the boolean conversion operator. E.g.: |
107 | /// |
108 | /// @code{.cpp} |
109 | /// Error foo(<...>); |
110 | /// |
111 | /// if (auto E = foo(<...>)) |
112 | /// return E; // <- Return E if it is in the error state. |
113 | /// // We have verified that E was in the success state. It can now be safely |
114 | /// // destroyed. |
115 | /// @endcode |
116 | /// |
117 | /// A success value *can not* be dropped. For example, just calling 'foo(<...>)' |
118 | /// without testing the return value will raise a runtime error, even if foo |
119 | /// returns success. |
120 | /// |
121 | /// For Error instances representing failure, you must use either the |
122 | /// handleErrors or handleAllErrors function with a typed handler. E.g.: |
123 | /// |
124 | /// @code{.cpp} |
125 | /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { |
126 | /// // Custom error info. |
127 | /// }; |
128 | /// |
129 | /// Error foo(<...>) { return make_error<MyErrorInfo>(...); } |
130 | /// |
131 | /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. |
132 | /// auto NewE = |
133 | /// handleErrors(E, |
134 | /// [](const MyErrorInfo &M) { |
135 | /// // Deal with the error. |
136 | /// }, |
137 | /// [](std::unique_ptr<OtherError> M) -> Error { |
138 | /// if (canHandle(*M)) { |
139 | /// // handle error. |
140 | /// return Error::success(); |
141 | /// } |
142 | /// // Couldn't handle this error instance. Pass it up the stack. |
143 | /// return Error(std::move(M)); |
144 | /// ); |
145 | /// // Note - we must check or return NewE in case any of the handlers |
146 | /// // returned a new error. |
147 | /// @endcode |
148 | /// |
149 | /// The handleAllErrors function is identical to handleErrors, except |
150 | /// that it has a void return type, and requires all errors to be handled and |
151 | /// no new errors be returned. It prevents errors (assuming they can all be |
152 | /// handled) from having to be bubbled all the way to the top-level. |
153 | /// |
154 | /// *All* Error instances must be checked before destruction, even if |
155 | /// they're moved-assigned or constructed from Success values that have already |
156 | /// been checked. This enforces checking through all levels of the call stack. |
157 | class LLVM_NODISCARD[[clang::warn_unused_result]] Error { |
158 | // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors |
159 | // to add to the error list. It can't rely on handleErrors for this, since |
160 | // handleErrors does not support ErrorList handlers. |
161 | friend class ErrorList; |
162 | |
163 | // handleErrors needs to be able to set the Checked flag. |
164 | template <typename... HandlerTs> |
165 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
166 | |
167 | // Expected<T> needs to be able to steal the payload when constructed from an |
168 | // error. |
169 | template <typename T> friend class Expected; |
170 | |
171 | // wrap needs to be able to steal the payload. |
172 | friend LLVMErrorRef wrap(Error); |
173 | |
174 | protected: |
175 | /// Create a success value. Prefer using 'Error::success()' for readability |
176 | Error() { |
177 | setPtr(nullptr); |
178 | setChecked(false); |
179 | } |
180 | |
181 | public: |
182 | /// Create a success value. |
183 | static ErrorSuccess success(); |
184 | |
185 | // Errors are not copy-constructable. |
186 | Error(const Error &Other) = delete; |
187 | |
188 | /// Move-construct an error value. The newly constructed error is considered |
189 | /// unchecked, even if the source error had been checked. The original error |
190 | /// becomes a checked Success value, regardless of its original state. |
191 | Error(Error &&Other) { |
192 | setChecked(true); |
193 | *this = std::move(Other); |
194 | } |
195 | |
196 | /// Create an error value. Prefer using the 'make_error' function, but |
197 | /// this constructor can be useful when "re-throwing" errors from handlers. |
198 | Error(std::unique_ptr<ErrorInfoBase> Payload) { |
199 | setPtr(Payload.release()); |
200 | setChecked(false); |
201 | } |
202 | |
203 | // Errors are not copy-assignable. |
204 | Error &operator=(const Error &Other) = delete; |
205 | |
206 | /// Move-assign an error value. The current error must represent success, you |
207 | /// you cannot overwrite an unhandled error. The current error is then |
208 | /// considered unchecked. The source error becomes a checked success value, |
209 | /// regardless of its original state. |
210 | Error &operator=(Error &&Other) { |
211 | // Don't allow overwriting of unchecked values. |
212 | assertIsChecked(); |
213 | setPtr(Other.getPtr()); |
214 | |
215 | // This Error is unchecked, even if the source error was checked. |
216 | setChecked(false); |
217 | |
218 | // Null out Other's payload and set its checked bit. |
219 | Other.setPtr(nullptr); |
220 | Other.setChecked(true); |
221 | |
222 | return *this; |
223 | } |
224 | |
225 | /// Destroy a Error. Fails with a call to abort() if the error is |
226 | /// unchecked. |
227 | ~Error() { |
228 | assertIsChecked(); |
229 | delete getPtr(); |
230 | } |
231 | |
232 | /// Bool conversion. Returns true if this Error is in a failure state, |
233 | /// and false if it is in an accept state. If the error is in a Success state |
234 | /// it will be considered checked. |
235 | explicit operator bool() { |
236 | setChecked(getPtr() == nullptr); |
237 | return getPtr() != nullptr; |
238 | } |
239 | |
240 | /// Check whether one error is a subclass of another. |
241 | template <typename ErrT> bool isA() const { |
242 | return getPtr() && getPtr()->isA(ErrT::classID()); |
243 | } |
244 | |
245 | /// Returns the dynamic class id of this error, or null if this is a success |
246 | /// value. |
247 | const void* dynamicClassID() const { |
248 | if (!getPtr()) |
249 | return nullptr; |
250 | return getPtr()->dynamicClassID(); |
251 | } |
252 | |
253 | private: |
254 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
255 | // assertIsChecked() happens very frequently, but under normal circumstances |
256 | // is supposed to be a no-op. So we want it to be inlined, but having a bunch |
257 | // of debug prints can cause the function to be too large for inlining. So |
258 | // it's important that we define this function out of line so that it can't be |
259 | // inlined. |
260 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) |
261 | void fatalUncheckedError() const; |
262 | #endif |
263 | |
264 | void assertIsChecked() { |
265 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
266 | if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false)) |
267 | fatalUncheckedError(); |
268 | #endif |
269 | } |
270 | |
271 | ErrorInfoBase *getPtr() const { |
272 | return reinterpret_cast<ErrorInfoBase*>( |
273 | reinterpret_cast<uintptr_t>(Payload) & |
274 | ~static_cast<uintptr_t>(0x1)); |
275 | } |
276 | |
277 | void setPtr(ErrorInfoBase *EI) { |
278 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
279 | Payload = reinterpret_cast<ErrorInfoBase*>( |
280 | (reinterpret_cast<uintptr_t>(EI) & |
281 | ~static_cast<uintptr_t>(0x1)) | |
282 | (reinterpret_cast<uintptr_t>(Payload) & 0x1)); |
283 | #else |
284 | Payload = EI; |
285 | #endif |
286 | } |
287 | |
288 | bool getChecked() const { |
289 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
290 | return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; |
291 | #else |
292 | return true; |
293 | #endif |
294 | } |
295 | |
296 | void setChecked(bool V) { |
297 | Payload = reinterpret_cast<ErrorInfoBase*>( |
298 | (reinterpret_cast<uintptr_t>(Payload) & |
299 | ~static_cast<uintptr_t>(0x1)) | |
300 | (V ? 0 : 1)); |
301 | } |
302 | |
303 | std::unique_ptr<ErrorInfoBase> takePayload() { |
304 | std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); |
305 | setPtr(nullptr); |
306 | setChecked(true); |
307 | return Tmp; |
308 | } |
309 | |
310 | friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { |
311 | if (auto P = E.getPtr()) |
312 | P->log(OS); |
313 | else |
314 | OS << "success"; |
315 | return OS; |
316 | } |
317 | |
318 | ErrorInfoBase *Payload = nullptr; |
319 | }; |
320 | |
321 | /// Subclass of Error for the sole purpose of identifying the success path in |
322 | /// the type system. This allows to catch invalid conversion to Expected<T> at |
323 | /// compile time. |
324 | class ErrorSuccess final : public Error {}; |
325 | |
326 | inline ErrorSuccess Error::success() { return ErrorSuccess(); } |
327 | |
328 | /// Make a Error instance representing failure using the given error info |
329 | /// type. |
330 | template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { |
331 | return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); |
332 | } |
333 | |
334 | /// Base class for user error types. Users should declare their error types |
335 | /// like: |
336 | /// |
337 | /// class MyError : public ErrorInfo<MyError> { |
338 | /// .... |
339 | /// }; |
340 | /// |
341 | /// This class provides an implementation of the ErrorInfoBase::kind |
342 | /// method, which is used by the Error RTTI system. |
343 | template <typename ThisErrT, typename ParentErrT = ErrorInfoBase> |
344 | class ErrorInfo : public ParentErrT { |
345 | public: |
346 | using ParentErrT::ParentErrT; // inherit constructors |
347 | |
348 | static const void *classID() { return &ThisErrT::ID; } |
349 | |
350 | const void *dynamicClassID() const override { return &ThisErrT::ID; } |
351 | |
352 | bool isA(const void *const ClassID) const override { |
353 | return ClassID == classID() || ParentErrT::isA(ClassID); |
354 | } |
355 | }; |
356 | |
357 | /// Special ErrorInfo subclass representing a list of ErrorInfos. |
358 | /// Instances of this class are constructed by joinError. |
359 | class ErrorList final : public ErrorInfo<ErrorList> { |
360 | // handleErrors needs to be able to iterate the payload list of an |
361 | // ErrorList. |
362 | template <typename... HandlerTs> |
363 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
364 | |
365 | // joinErrors is implemented in terms of join. |
366 | friend Error joinErrors(Error, Error); |
367 | |
368 | public: |
369 | void log(raw_ostream &OS) const override { |
370 | OS << "Multiple errors:\n"; |
371 | for (auto &ErrPayload : Payloads) { |
372 | ErrPayload->log(OS); |
373 | OS << "\n"; |
374 | } |
375 | } |
376 | |
377 | std::error_code convertToErrorCode() const override; |
378 | |
379 | // Used by ErrorInfo::classID. |
380 | static char ID; |
381 | |
382 | private: |
383 | ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, |
384 | std::unique_ptr<ErrorInfoBase> Payload2) { |
385 | assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((!Payload1->isA<ErrorList>() && !Payload2-> isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors" ) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 386, __PRETTY_FUNCTION__)) |
386 | "ErrorList constructor payloads should be singleton errors")((!Payload1->isA<ErrorList>() && !Payload2-> isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors" ) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 386, __PRETTY_FUNCTION__)); |
387 | Payloads.push_back(std::move(Payload1)); |
388 | Payloads.push_back(std::move(Payload2)); |
389 | } |
390 | |
391 | static Error join(Error E1, Error E2) { |
392 | if (!E1) |
393 | return E2; |
394 | if (!E2) |
395 | return E1; |
396 | if (E1.isA<ErrorList>()) { |
397 | auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); |
398 | if (E2.isA<ErrorList>()) { |
399 | auto E2Payload = E2.takePayload(); |
400 | auto &E2List = static_cast<ErrorList &>(*E2Payload); |
401 | for (auto &Payload : E2List.Payloads) |
402 | E1List.Payloads.push_back(std::move(Payload)); |
403 | } else |
404 | E1List.Payloads.push_back(E2.takePayload()); |
405 | |
406 | return E1; |
407 | } |
408 | if (E2.isA<ErrorList>()) { |
409 | auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); |
410 | E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); |
411 | return E2; |
412 | } |
413 | return Error(std::unique_ptr<ErrorList>( |
414 | new ErrorList(E1.takePayload(), E2.takePayload()))); |
415 | } |
416 | |
417 | std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; |
418 | }; |
419 | |
420 | /// Concatenate errors. The resulting Error is unchecked, and contains the |
421 | /// ErrorInfo(s), if any, contained in E1, followed by the |
422 | /// ErrorInfo(s), if any, contained in E2. |
423 | inline Error joinErrors(Error E1, Error E2) { |
424 | return ErrorList::join(std::move(E1), std::move(E2)); |
425 | } |
426 | |
427 | /// Tagged union holding either a T or a Error. |
428 | /// |
429 | /// This class parallels ErrorOr, but replaces error_code with Error. Since |
430 | /// Error cannot be copied, this class replaces getError() with |
431 | /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the |
432 | /// error class type. |
433 | template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected { |
434 | template <class T1> friend class ExpectedAsOutParameter; |
435 | template <class OtherT> friend class Expected; |
436 | |
437 | static const bool isRef = std::is_reference<T>::value; |
438 | |
439 | using wrap = std::reference_wrapper<std::remove_reference_t<T>>; |
440 | |
441 | using error_type = std::unique_ptr<ErrorInfoBase>; |
442 | |
443 | public: |
444 | using storage_type = std::conditional_t<isRef, wrap, T>; |
445 | using value_type = T; |
446 | |
447 | private: |
448 | using reference = std::remove_reference_t<T> &; |
449 | using const_reference = const std::remove_reference_t<T> &; |
450 | using pointer = std::remove_reference_t<T> *; |
451 | using const_pointer = const std::remove_reference_t<T> *; |
452 | |
453 | public: |
454 | /// Create an Expected<T> error value from the given Error. |
455 | Expected(Error Err) |
456 | : HasError(true) |
457 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
458 | // Expected is unchecked upon construction in Debug builds. |
459 | , Unchecked(true) |
460 | #endif |
461 | { |
462 | assert(Err && "Cannot create Expected<T> from Error success value.")((Err && "Cannot create Expected<T> from Error success value." ) ? static_cast<void> (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 462, __PRETTY_FUNCTION__)); |
463 | new (getErrorStorage()) error_type(Err.takePayload()); |
464 | } |
465 | |
466 | /// Forbid to convert from Error::success() implicitly, this avoids having |
467 | /// Expected<T> foo() { return Error::success(); } which compiles otherwise |
468 | /// but triggers the assertion above. |
469 | Expected(ErrorSuccess) = delete; |
470 | |
471 | /// Create an Expected<T> success value from the given OtherT value, which |
472 | /// must be convertible to T. |
473 | template <typename OtherT> |
474 | Expected(OtherT &&Val, |
475 | std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) |
476 | : HasError(false) |
477 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
478 | // Expected is unchecked upon construction in Debug builds. |
479 | , |
480 | Unchecked(true) |
481 | #endif |
482 | { |
483 | new (getStorage()) storage_type(std::forward<OtherT>(Val)); |
484 | } |
485 | |
486 | /// Move construct an Expected<T> value. |
487 | Expected(Expected &&Other) { moveConstruct(std::move(Other)); } |
488 | |
489 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
490 | /// must be convertible to T. |
491 | template <class OtherT> |
492 | Expected( |
493 | Expected<OtherT> &&Other, |
494 | std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) { |
495 | moveConstruct(std::move(Other)); |
496 | } |
497 | |
498 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
499 | /// isn't convertible to T. |
500 | template <class OtherT> |
501 | explicit Expected( |
502 | Expected<OtherT> &&Other, |
503 | std::enable_if_t<!std::is_convertible<OtherT, T>::value> * = nullptr) { |
504 | moveConstruct(std::move(Other)); |
505 | } |
506 | |
507 | /// Move-assign from another Expected<T>. |
508 | Expected &operator=(Expected &&Other) { |
509 | moveAssign(std::move(Other)); |
510 | return *this; |
511 | } |
512 | |
513 | /// Destroy an Expected<T>. |
514 | ~Expected() { |
515 | assertIsChecked(); |
516 | if (!HasError) |
517 | getStorage()->~storage_type(); |
518 | else |
519 | getErrorStorage()->~error_type(); |
520 | } |
521 | |
522 | /// Return false if there is an error. |
523 | explicit operator bool() { |
524 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
525 | Unchecked = HasError; |
526 | #endif |
527 | return !HasError; |
528 | } |
529 | |
530 | /// Returns a reference to the stored T value. |
531 | reference get() { |
532 | assertIsChecked(); |
533 | return *getStorage(); |
534 | } |
535 | |
536 | /// Returns a const reference to the stored T value. |
537 | const_reference get() const { |
538 | assertIsChecked(); |
539 | return const_cast<Expected<T> *>(this)->get(); |
540 | } |
541 | |
542 | /// Check that this Expected<T> is an error of type ErrT. |
543 | template <typename ErrT> bool errorIsA() const { |
544 | return HasError && (*getErrorStorage())->template isA<ErrT>(); |
545 | } |
546 | |
547 | /// Take ownership of the stored error. |
548 | /// After calling this the Expected<T> is in an indeterminate state that can |
549 | /// only be safely destructed. No further calls (beside the destructor) should |
550 | /// be made on the Expected<T> value. |
551 | Error takeError() { |
552 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
553 | Unchecked = false; |
554 | #endif |
555 | return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); |
556 | } |
557 | |
558 | /// Returns a pointer to the stored T value. |
559 | pointer operator->() { |
560 | assertIsChecked(); |
561 | return toPointer(getStorage()); |
562 | } |
563 | |
564 | /// Returns a const pointer to the stored T value. |
565 | const_pointer operator->() const { |
566 | assertIsChecked(); |
567 | return toPointer(getStorage()); |
568 | } |
569 | |
570 | /// Returns a reference to the stored T value. |
571 | reference operator*() { |
572 | assertIsChecked(); |
573 | return *getStorage(); |
574 | } |
575 | |
576 | /// Returns a const reference to the stored T value. |
577 | const_reference operator*() const { |
578 | assertIsChecked(); |
579 | return *getStorage(); |
580 | } |
581 | |
582 | private: |
583 | template <class T1> |
584 | static bool compareThisIfSameType(const T1 &a, const T1 &b) { |
585 | return &a == &b; |
586 | } |
587 | |
588 | template <class T1, class T2> |
589 | static bool compareThisIfSameType(const T1 &a, const T2 &b) { |
590 | return false; |
591 | } |
592 | |
593 | template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { |
594 | HasError = Other.HasError; |
595 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
596 | Unchecked = true; |
597 | Other.Unchecked = false; |
598 | #endif |
599 | |
600 | if (!HasError) |
601 | new (getStorage()) storage_type(std::move(*Other.getStorage())); |
602 | else |
603 | new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); |
604 | } |
605 | |
606 | template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { |
607 | assertIsChecked(); |
608 | |
609 | if (compareThisIfSameType(*this, Other)) |
610 | return; |
611 | |
612 | this->~Expected(); |
613 | new (this) Expected(std::move(Other)); |
614 | } |
615 | |
616 | pointer toPointer(pointer Val) { return Val; } |
617 | |
618 | const_pointer toPointer(const_pointer Val) const { return Val; } |
619 | |
620 | pointer toPointer(wrap *Val) { return &Val->get(); } |
621 | |
622 | const_pointer toPointer(const wrap *Val) const { return &Val->get(); } |
623 | |
624 | storage_type *getStorage() { |
625 | assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!" ) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 625, __PRETTY_FUNCTION__)); |
626 | return reinterpret_cast<storage_type *>(TStorage.buffer); |
627 | } |
628 | |
629 | const storage_type *getStorage() const { |
630 | assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!" ) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 630, __PRETTY_FUNCTION__)); |
631 | return reinterpret_cast<const storage_type *>(TStorage.buffer); |
632 | } |
633 | |
634 | error_type *getErrorStorage() { |
635 | assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!" ) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 635, __PRETTY_FUNCTION__)); |
636 | return reinterpret_cast<error_type *>(ErrorStorage.buffer); |
637 | } |
638 | |
639 | const error_type *getErrorStorage() const { |
640 | assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!" ) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 640, __PRETTY_FUNCTION__)); |
641 | return reinterpret_cast<const error_type *>(ErrorStorage.buffer); |
642 | } |
643 | |
644 | // Used by ExpectedAsOutParameter to reset the checked flag. |
645 | void setUnchecked() { |
646 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
647 | Unchecked = true; |
648 | #endif |
649 | } |
650 | |
651 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
652 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) |
653 | LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) |
654 | void fatalUncheckedExpected() const { |
655 | dbgs() << "Expected<T> must be checked before access or destruction.\n"; |
656 | if (HasError) { |
657 | dbgs() << "Unchecked Expected<T> contained error:\n"; |
658 | (*getErrorStorage())->log(dbgs()); |
659 | } else |
660 | dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " |
661 | "values in success mode must still be checked prior to being " |
662 | "destroyed).\n"; |
663 | abort(); |
664 | } |
665 | #endif |
666 | |
667 | void assertIsChecked() { |
668 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
669 | if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false)) |
670 | fatalUncheckedExpected(); |
671 | #endif |
672 | } |
673 | |
674 | union { |
675 | AlignedCharArrayUnion<storage_type> TStorage; |
676 | AlignedCharArrayUnion<error_type> ErrorStorage; |
677 | }; |
678 | bool HasError : 1; |
679 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
680 | bool Unchecked : 1; |
681 | #endif |
682 | }; |
683 | |
684 | /// Report a serious error, calling any installed error handler. See |
685 | /// ErrorHandling.h. |
686 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err, |
687 | bool gen_crash_diag = true); |
688 | |
689 | /// Report a fatal error if Err is a failure value. |
690 | /// |
691 | /// This function can be used to wrap calls to fallible functions ONLY when it |
692 | /// is known that the Error will always be a success value. E.g. |
693 | /// |
694 | /// @code{.cpp} |
695 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
696 | /// // true. If DoFallibleOperation is false then foo always returns |
697 | /// // Error::success(). |
698 | /// Error foo(bool DoFallibleOperation); |
699 | /// |
700 | /// cantFail(foo(false)); |
701 | /// @endcode |
702 | inline void cantFail(Error Err, const char *Msg = nullptr) { |
703 | if (Err) { |
704 | if (!Msg) |
705 | Msg = "Failure value returned from cantFail wrapped call"; |
706 | #ifndef NDEBUG |
707 | std::string Str; |
708 | raw_string_ostream OS(Str); |
709 | OS << Msg << "\n" << Err; |
710 | Msg = OS.str().c_str(); |
711 | #endif |
712 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 712); |
713 | } |
714 | } |
715 | |
716 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
717 | /// returns the contained value. |
718 | /// |
719 | /// This function can be used to wrap calls to fallible functions ONLY when it |
720 | /// is known that the Error will always be a success value. E.g. |
721 | /// |
722 | /// @code{.cpp} |
723 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
724 | /// // true. If DoFallibleOperation is false then foo always returns an int. |
725 | /// Expected<int> foo(bool DoFallibleOperation); |
726 | /// |
727 | /// int X = cantFail(foo(false)); |
728 | /// @endcode |
729 | template <typename T> |
730 | T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { |
731 | if (ValOrErr) |
732 | return std::move(*ValOrErr); |
733 | else { |
734 | if (!Msg) |
735 | Msg = "Failure value returned from cantFail wrapped call"; |
736 | #ifndef NDEBUG |
737 | std::string Str; |
738 | raw_string_ostream OS(Str); |
739 | auto E = ValOrErr.takeError(); |
740 | OS << Msg << "\n" << E; |
741 | Msg = OS.str().c_str(); |
742 | #endif |
743 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 743); |
744 | } |
745 | } |
746 | |
747 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
748 | /// returns the contained reference. |
749 | /// |
750 | /// This function can be used to wrap calls to fallible functions ONLY when it |
751 | /// is known that the Error will always be a success value. E.g. |
752 | /// |
753 | /// @code{.cpp} |
754 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
755 | /// // true. If DoFallibleOperation is false then foo always returns a Bar&. |
756 | /// Expected<Bar&> foo(bool DoFallibleOperation); |
757 | /// |
758 | /// Bar &X = cantFail(foo(false)); |
759 | /// @endcode |
760 | template <typename T> |
761 | T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { |
762 | if (ValOrErr) |
763 | return *ValOrErr; |
764 | else { |
765 | if (!Msg) |
766 | Msg = "Failure value returned from cantFail wrapped call"; |
767 | #ifndef NDEBUG |
768 | std::string Str; |
769 | raw_string_ostream OS(Str); |
770 | auto E = ValOrErr.takeError(); |
771 | OS << Msg << "\n" << E; |
772 | Msg = OS.str().c_str(); |
773 | #endif |
774 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 774); |
775 | } |
776 | } |
777 | |
778 | /// Helper for testing applicability of, and applying, handlers for |
779 | /// ErrorInfo types. |
780 | template <typename HandlerT> |
781 | class ErrorHandlerTraits |
782 | : public ErrorHandlerTraits<decltype( |
783 | &std::remove_reference<HandlerT>::type::operator())> {}; |
784 | |
785 | // Specialization functions of the form 'Error (const ErrT&)'. |
786 | template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { |
787 | public: |
788 | static bool appliesTo(const ErrorInfoBase &E) { |
789 | return E.template isA<ErrT>(); |
790 | } |
791 | |
792 | template <typename HandlerT> |
793 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
794 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 794, __PRETTY_FUNCTION__)); |
795 | return H(static_cast<ErrT &>(*E)); |
796 | } |
797 | }; |
798 | |
799 | // Specialization functions of the form 'void (const ErrT&)'. |
800 | template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { |
801 | public: |
802 | static bool appliesTo(const ErrorInfoBase &E) { |
803 | return E.template isA<ErrT>(); |
804 | } |
805 | |
806 | template <typename HandlerT> |
807 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
808 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 808, __PRETTY_FUNCTION__)); |
809 | H(static_cast<ErrT &>(*E)); |
810 | return Error::success(); |
811 | } |
812 | }; |
813 | |
814 | /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. |
815 | template <typename ErrT> |
816 | class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { |
817 | public: |
818 | static bool appliesTo(const ErrorInfoBase &E) { |
819 | return E.template isA<ErrT>(); |
820 | } |
821 | |
822 | template <typename HandlerT> |
823 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
824 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 824, __PRETTY_FUNCTION__)); |
825 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
826 | return H(std::move(SubE)); |
827 | } |
828 | }; |
829 | |
830 | /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. |
831 | template <typename ErrT> |
832 | class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { |
833 | public: |
834 | static bool appliesTo(const ErrorInfoBase &E) { |
835 | return E.template isA<ErrT>(); |
836 | } |
837 | |
838 | template <typename HandlerT> |
839 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
840 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 840, __PRETTY_FUNCTION__)); |
841 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
842 | H(std::move(SubE)); |
843 | return Error::success(); |
844 | } |
845 | }; |
846 | |
847 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
848 | template <typename C, typename RetT, typename ErrT> |
849 | class ErrorHandlerTraits<RetT (C::*)(ErrT &)> |
850 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
851 | |
852 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
853 | template <typename C, typename RetT, typename ErrT> |
854 | class ErrorHandlerTraits<RetT (C::*)(ErrT &) const> |
855 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
856 | |
857 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
858 | template <typename C, typename RetT, typename ErrT> |
859 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &)> |
860 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
861 | |
862 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
863 | template <typename C, typename RetT, typename ErrT> |
864 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> |
865 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
866 | |
867 | /// Specialization for member functions of the form |
868 | /// 'RetT (std::unique_ptr<ErrT>)'. |
869 | template <typename C, typename RetT, typename ErrT> |
870 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> |
871 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
872 | |
873 | /// Specialization for member functions of the form |
874 | /// 'RetT (std::unique_ptr<ErrT>) const'. |
875 | template <typename C, typename RetT, typename ErrT> |
876 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> |
877 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
878 | |
879 | inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { |
880 | return Error(std::move(Payload)); |
881 | } |
882 | |
883 | template <typename HandlerT, typename... HandlerTs> |
884 | Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, |
885 | HandlerT &&Handler, HandlerTs &&... Handlers) { |
886 | if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) |
887 | return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), |
888 | std::move(Payload)); |
889 | return handleErrorImpl(std::move(Payload), |
890 | std::forward<HandlerTs>(Handlers)...); |
891 | } |
892 | |
893 | /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any |
894 | /// unhandled errors (or Errors returned by handlers) are re-concatenated and |
895 | /// returned. |
896 | /// Because this function returns an error, its result must also be checked |
897 | /// or returned. If you intend to handle all errors use handleAllErrors |
898 | /// (which returns void, and will abort() on unhandled errors) instead. |
899 | template <typename... HandlerTs> |
900 | Error handleErrors(Error E, HandlerTs &&... Hs) { |
901 | if (!E) |
902 | return Error::success(); |
903 | |
904 | std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); |
905 | |
906 | if (Payload->isA<ErrorList>()) { |
907 | ErrorList &List = static_cast<ErrorList &>(*Payload); |
908 | Error R; |
909 | for (auto &P : List.Payloads) |
910 | R = ErrorList::join( |
911 | std::move(R), |
912 | handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); |
913 | return R; |
914 | } |
915 | |
916 | return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); |
917 | } |
918 | |
919 | /// Behaves the same as handleErrors, except that by contract all errors |
920 | /// *must* be handled by the given handlers (i.e. there must be no remaining |
921 | /// errors after running the handlers, or llvm_unreachable is called). |
922 | template <typename... HandlerTs> |
923 | void handleAllErrors(Error E, HandlerTs &&... Handlers) { |
924 | cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); |
925 | } |
926 | |
927 | /// Check that E is a non-error, then drop it. |
928 | /// If E is an error, llvm_unreachable will be called. |
929 | inline void handleAllErrors(Error E) { |
930 | cantFail(std::move(E)); |
931 | } |
932 | |
933 | /// Handle any errors (if present) in an Expected<T>, then try a recovery path. |
934 | /// |
935 | /// If the incoming value is a success value it is returned unmodified. If it |
936 | /// is a failure value then it the contained error is passed to handleErrors. |
937 | /// If handleErrors is able to handle the error then the RecoveryPath functor |
938 | /// is called to supply the final result. If handleErrors is not able to |
939 | /// handle all errors then the unhandled errors are returned. |
940 | /// |
941 | /// This utility enables the follow pattern: |
942 | /// |
943 | /// @code{.cpp} |
944 | /// enum FooStrategy { Aggressive, Conservative }; |
945 | /// Expected<Foo> foo(FooStrategy S); |
946 | /// |
947 | /// auto ResultOrErr = |
948 | /// handleExpected( |
949 | /// foo(Aggressive), |
950 | /// []() { return foo(Conservative); }, |
951 | /// [](AggressiveStrategyError&) { |
952 | /// // Implicitly conusme this - we'll recover by using a conservative |
953 | /// // strategy. |
954 | /// }); |
955 | /// |
956 | /// @endcode |
957 | template <typename T, typename RecoveryFtor, typename... HandlerTs> |
958 | Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, |
959 | HandlerTs &&... Handlers) { |
960 | if (ValOrErr) |
961 | return ValOrErr; |
962 | |
963 | if (auto Err = handleErrors(ValOrErr.takeError(), |
964 | std::forward<HandlerTs>(Handlers)...)) |
965 | return std::move(Err); |
966 | |
967 | return RecoveryPath(); |
968 | } |
969 | |
970 | /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner |
971 | /// will be printed before the first one is logged. A newline will be printed |
972 | /// after each error. |
973 | /// |
974 | /// This function is compatible with the helpers from Support/WithColor.h. You |
975 | /// can pass any of them as the OS. Please consider using them instead of |
976 | /// including 'error: ' in the ErrorBanner. |
977 | /// |
978 | /// This is useful in the base level of your program to allow clean termination |
979 | /// (allowing clean deallocation of resources, etc.), while reporting error |
980 | /// information to the user. |
981 | void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {}); |
982 | |
983 | /// Write all error messages (if any) in E to a string. The newline character |
984 | /// is used to separate error messages. |
985 | inline std::string toString(Error E) { |
986 | SmallVector<std::string, 2> Errors; |
987 | handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { |
988 | Errors.push_back(EI.message()); |
989 | }); |
990 | return join(Errors.begin(), Errors.end(), "\n"); |
991 | } |
992 | |
993 | /// Consume a Error without doing anything. This method should be used |
994 | /// only where an error can be considered a reasonable and expected return |
995 | /// value. |
996 | /// |
997 | /// Uses of this method are potentially indicative of design problems: If it's |
998 | /// legitimate to do nothing while processing an "error", the error-producer |
999 | /// might be more clearly refactored to return an Optional<T>. |
1000 | inline void consumeError(Error Err) { |
1001 | handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); |
1002 | } |
1003 | |
1004 | /// Convert an Expected to an Optional without doing anything. This method |
1005 | /// should be used only where an error can be considered a reasonable and |
1006 | /// expected return value. |
1007 | /// |
1008 | /// Uses of this method are potentially indicative of problems: perhaps the |
1009 | /// error should be propagated further, or the error-producer should just |
1010 | /// return an Optional in the first place. |
1011 | template <typename T> Optional<T> expectedToOptional(Expected<T> &&E) { |
1012 | if (E) |
1013 | return std::move(*E); |
1014 | consumeError(E.takeError()); |
1015 | return None; |
1016 | } |
1017 | |
1018 | /// Helper for converting an Error to a bool. |
1019 | /// |
1020 | /// This method returns true if Err is in an error state, or false if it is |
1021 | /// in a success state. Puts Err in a checked state in both cases (unlike |
1022 | /// Error::operator bool(), which only does this for success states). |
1023 | inline bool errorToBool(Error Err) { |
1024 | bool IsError = static_cast<bool>(Err); |
1025 | if (IsError) |
1026 | consumeError(std::move(Err)); |
1027 | return IsError; |
1028 | } |
1029 | |
1030 | /// Helper for Errors used as out-parameters. |
1031 | /// |
1032 | /// This helper is for use with the Error-as-out-parameter idiom, where an error |
1033 | /// is passed to a function or method by reference, rather than being returned. |
1034 | /// In such cases it is helpful to set the checked bit on entry to the function |
1035 | /// so that the error can be written to (unchecked Errors abort on assignment) |
1036 | /// and clear the checked bit on exit so that clients cannot accidentally forget |
1037 | /// to check the result. This helper performs these actions automatically using |
1038 | /// RAII: |
1039 | /// |
1040 | /// @code{.cpp} |
1041 | /// Result foo(Error &Err) { |
1042 | /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set |
1043 | /// // <body of foo> |
1044 | /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. |
1045 | /// } |
1046 | /// @endcode |
1047 | /// |
1048 | /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be |
1049 | /// used with optional Errors (Error pointers that are allowed to be null). If |
1050 | /// ErrorAsOutParameter took an Error reference, an instance would have to be |
1051 | /// created inside every condition that verified that Error was non-null. By |
1052 | /// taking an Error pointer we can just create one instance at the top of the |
1053 | /// function. |
1054 | class ErrorAsOutParameter { |
1055 | public: |
1056 | ErrorAsOutParameter(Error *Err) : Err(Err) { |
1057 | // Raise the checked bit if Err is success. |
1058 | if (Err) |
1059 | (void)!!*Err; |
1060 | } |
1061 | |
1062 | ~ErrorAsOutParameter() { |
1063 | // Clear the checked bit. |
1064 | if (Err && !*Err) |
1065 | *Err = Error::success(); |
1066 | } |
1067 | |
1068 | private: |
1069 | Error *Err; |
1070 | }; |
1071 | |
1072 | /// Helper for Expected<T>s used as out-parameters. |
1073 | /// |
1074 | /// See ErrorAsOutParameter. |
1075 | template <typename T> |
1076 | class ExpectedAsOutParameter { |
1077 | public: |
1078 | ExpectedAsOutParameter(Expected<T> *ValOrErr) |
1079 | : ValOrErr(ValOrErr) { |
1080 | if (ValOrErr) |
1081 | (void)!!*ValOrErr; |
1082 | } |
1083 | |
1084 | ~ExpectedAsOutParameter() { |
1085 | if (ValOrErr) |
1086 | ValOrErr->setUnchecked(); |
1087 | } |
1088 | |
1089 | private: |
1090 | Expected<T> *ValOrErr; |
1091 | }; |
1092 | |
1093 | /// This class wraps a std::error_code in a Error. |
1094 | /// |
1095 | /// This is useful if you're writing an interface that returns a Error |
1096 | /// (or Expected) and you want to call code that still returns |
1097 | /// std::error_codes. |
1098 | class ECError : public ErrorInfo<ECError> { |
1099 | friend Error errorCodeToError(std::error_code); |
1100 | |
1101 | virtual void anchor() override; |
1102 | |
1103 | public: |
1104 | void setErrorCode(std::error_code EC) { this->EC = EC; } |
1105 | std::error_code convertToErrorCode() const override { return EC; } |
1106 | void log(raw_ostream &OS) const override { OS << EC.message(); } |
1107 | |
1108 | // Used by ErrorInfo::classID. |
1109 | static char ID; |
1110 | |
1111 | protected: |
1112 | ECError() = default; |
1113 | ECError(std::error_code EC) : EC(EC) {} |
1114 | |
1115 | std::error_code EC; |
1116 | }; |
1117 | |
1118 | /// The value returned by this function can be returned from convertToErrorCode |
1119 | /// for Error values where no sensible translation to std::error_code exists. |
1120 | /// It should only be used in this situation, and should never be used where a |
1121 | /// sensible conversion to std::error_code is available, as attempts to convert |
1122 | /// to/from this error will result in a fatal error. (i.e. it is a programmatic |
1123 | ///error to try to convert such a value). |
1124 | std::error_code inconvertibleErrorCode(); |
1125 | |
1126 | /// Helper for converting an std::error_code to a Error. |
1127 | Error errorCodeToError(std::error_code EC); |
1128 | |
1129 | /// Helper for converting an ECError to a std::error_code. |
1130 | /// |
1131 | /// This method requires that Err be Error() or an ECError, otherwise it |
1132 | /// will trigger a call to abort(). |
1133 | std::error_code errorToErrorCode(Error Err); |
1134 | |
1135 | /// Convert an ErrorOr<T> to an Expected<T>. |
1136 | template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { |
1137 | if (auto EC = EO.getError()) |
1138 | return errorCodeToError(EC); |
1139 | return std::move(*EO); |
1140 | } |
1141 | |
1142 | /// Convert an Expected<T> to an ErrorOr<T>. |
1143 | template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { |
1144 | if (auto Err = E.takeError()) |
1145 | return errorToErrorCode(std::move(Err)); |
1146 | return std::move(*E); |
1147 | } |
1148 | |
1149 | /// This class wraps a string in an Error. |
1150 | /// |
1151 | /// StringError is useful in cases where the client is not expected to be able |
1152 | /// to consume the specific error message programmatically (for example, if the |
1153 | /// error message is to be presented to the user). |
1154 | /// |
1155 | /// StringError can also be used when additional information is to be printed |
1156 | /// along with a error_code message. Depending on the constructor called, this |
1157 | /// class can either display: |
1158 | /// 1. the error_code message (ECError behavior) |
1159 | /// 2. a string |
1160 | /// 3. the error_code message and a string |
1161 | /// |
1162 | /// These behaviors are useful when subtyping is required; for example, when a |
1163 | /// specific library needs an explicit error type. In the example below, |
1164 | /// PDBError is derived from StringError: |
1165 | /// |
1166 | /// @code{.cpp} |
1167 | /// Expected<int> foo() { |
1168 | /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, |
1169 | /// "Additional information"); |
1170 | /// } |
1171 | /// @endcode |
1172 | /// |
1173 | class StringError : public ErrorInfo<StringError> { |
1174 | public: |
1175 | static char ID; |
1176 | |
1177 | // Prints EC + S and converts to EC |
1178 | StringError(std::error_code EC, const Twine &S = Twine()); |
1179 | |
1180 | // Prints S and converts to EC |
1181 | StringError(const Twine &S, std::error_code EC); |
1182 | |
1183 | void log(raw_ostream &OS) const override; |
1184 | std::error_code convertToErrorCode() const override; |
1185 | |
1186 | const std::string &getMessage() const { return Msg; } |
1187 | |
1188 | private: |
1189 | std::string Msg; |
1190 | std::error_code EC; |
1191 | const bool PrintMsgOnly = false; |
1192 | }; |
1193 | |
1194 | /// Create formatted StringError object. |
1195 | template <typename... Ts> |
1196 | inline Error createStringError(std::error_code EC, char const *Fmt, |
1197 | const Ts &... Vals) { |
1198 | std::string Buffer; |
1199 | raw_string_ostream Stream(Buffer); |
1200 | Stream << format(Fmt, Vals...); |
1201 | return make_error<StringError>(Stream.str(), EC); |
1202 | } |
1203 | |
1204 | Error createStringError(std::error_code EC, char const *Msg); |
1205 | |
1206 | inline Error createStringError(std::error_code EC, const Twine &S) { |
1207 | return createStringError(EC, S.str().c_str()); |
1208 | } |
1209 | |
1210 | template <typename... Ts> |
1211 | inline Error createStringError(std::errc EC, char const *Fmt, |
1212 | const Ts &... Vals) { |
1213 | return createStringError(std::make_error_code(EC), Fmt, Vals...); |
1214 | } |
1215 | |
1216 | /// This class wraps a filename and another Error. |
1217 | /// |
1218 | /// In some cases, an error needs to live along a 'source' name, in order to |
1219 | /// show more detailed information to the user. |
1220 | class FileError final : public ErrorInfo<FileError> { |
1221 | |
1222 | friend Error createFileError(const Twine &, Error); |
1223 | friend Error createFileError(const Twine &, size_t, Error); |
1224 | |
1225 | public: |
1226 | void log(raw_ostream &OS) const override { |
1227 | assert(Err && !FileName.empty() && "Trying to log after takeError().")((Err && !FileName.empty() && "Trying to log after takeError()." ) ? static_cast<void> (0) : __assert_fail ("Err && !FileName.empty() && \"Trying to log after takeError().\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 1227, __PRETTY_FUNCTION__)); |
1228 | OS << "'" << FileName << "': "; |
1229 | if (Line.hasValue()) |
1230 | OS << "line " << Line.getValue() << ": "; |
1231 | Err->log(OS); |
1232 | } |
1233 | |
1234 | StringRef getFileName() { return FileName; } |
1235 | |
1236 | Error takeError() { return Error(std::move(Err)); } |
1237 | |
1238 | std::error_code convertToErrorCode() const override; |
1239 | |
1240 | // Used by ErrorInfo::classID. |
1241 | static char ID; |
1242 | |
1243 | private: |
1244 | FileError(const Twine &F, Optional<size_t> LineNum, |
1245 | std::unique_ptr<ErrorInfoBase> E) { |
1246 | assert(E && "Cannot create FileError from Error success value.")((E && "Cannot create FileError from Error success value." ) ? static_cast<void> (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 1246, __PRETTY_FUNCTION__)); |
1247 | assert(!F.isTriviallyEmpty() &&((!F.isTriviallyEmpty() && "The file name provided to FileError must not be empty." ) ? static_cast<void> (0) : __assert_fail ("!F.isTriviallyEmpty() && \"The file name provided to FileError must not be empty.\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 1248, __PRETTY_FUNCTION__)) |
1248 | "The file name provided to FileError must not be empty.")((!F.isTriviallyEmpty() && "The file name provided to FileError must not be empty." ) ? static_cast<void> (0) : __assert_fail ("!F.isTriviallyEmpty() && \"The file name provided to FileError must not be empty.\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 1248, __PRETTY_FUNCTION__)); |
1249 | FileName = F.str(); |
1250 | Err = std::move(E); |
1251 | Line = std::move(LineNum); |
1252 | } |
1253 | |
1254 | static Error build(const Twine &F, Optional<size_t> Line, Error E) { |
1255 | std::unique_ptr<ErrorInfoBase> Payload; |
1256 | handleAllErrors(std::move(E), |
1257 | [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error { |
1258 | Payload = std::move(EIB); |
1259 | return Error::success(); |
1260 | }); |
1261 | return Error( |
1262 | std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload)))); |
1263 | } |
1264 | |
1265 | std::string FileName; |
1266 | Optional<size_t> Line; |
1267 | std::unique_ptr<ErrorInfoBase> Err; |
1268 | }; |
1269 | |
1270 | /// Concatenate a source file path and/or name with an Error. The resulting |
1271 | /// Error is unchecked. |
1272 | inline Error createFileError(const Twine &F, Error E) { |
1273 | return FileError::build(F, Optional<size_t>(), std::move(E)); |
1274 | } |
1275 | |
1276 | /// Concatenate a source file path and/or name with line number and an Error. |
1277 | /// The resulting Error is unchecked. |
1278 | inline Error createFileError(const Twine &F, size_t Line, Error E) { |
1279 | return FileError::build(F, Optional<size_t>(Line), std::move(E)); |
1280 | } |
1281 | |
1282 | /// Concatenate a source file path and/or name with a std::error_code |
1283 | /// to form an Error object. |
1284 | inline Error createFileError(const Twine &F, std::error_code EC) { |
1285 | return createFileError(F, errorCodeToError(EC)); |
1286 | } |
1287 | |
1288 | /// Concatenate a source file path and/or name with line number and |
1289 | /// std::error_code to form an Error object. |
1290 | inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) { |
1291 | return createFileError(F, Line, errorCodeToError(EC)); |
1292 | } |
1293 | |
1294 | Error createFileError(const Twine &F, ErrorSuccess) = delete; |
1295 | |
1296 | /// Helper for check-and-exit error handling. |
1297 | /// |
1298 | /// For tool use only. NOT FOR USE IN LIBRARY CODE. |
1299 | /// |
1300 | class ExitOnError { |
1301 | public: |
1302 | /// Create an error on exit helper. |
1303 | ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) |
1304 | : Banner(std::move(Banner)), |
1305 | GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} |
1306 | |
1307 | /// Set the banner string for any errors caught by operator(). |
1308 | void setBanner(std::string Banner) { this->Banner = std::move(Banner); } |
1309 | |
1310 | /// Set the exit-code mapper function. |
1311 | void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { |
1312 | this->GetExitCode = std::move(GetExitCode); |
1313 | } |
1314 | |
1315 | /// Check Err. If it's in a failure state log the error(s) and exit. |
1316 | void operator()(Error Err) const { checkError(std::move(Err)); } |
1317 | |
1318 | /// Check E. If it's in a success state then return the contained value. If |
1319 | /// it's in a failure state log the error(s) and exit. |
1320 | template <typename T> T operator()(Expected<T> &&E) const { |
1321 | checkError(E.takeError()); |
1322 | return std::move(*E); |
1323 | } |
1324 | |
1325 | /// Check E. If it's in a success state then return the contained reference. If |
1326 | /// it's in a failure state log the error(s) and exit. |
1327 | template <typename T> T& operator()(Expected<T&> &&E) const { |
1328 | checkError(E.takeError()); |
1329 | return *E; |
1330 | } |
1331 | |
1332 | private: |
1333 | void checkError(Error Err) const { |
1334 | if (Err) { |
1335 | int ExitCode = GetExitCode(Err); |
1336 | logAllUnhandledErrors(std::move(Err), errs(), Banner); |
1337 | exit(ExitCode); |
1338 | } |
1339 | } |
1340 | |
1341 | std::string Banner; |
1342 | std::function<int(const Error &)> GetExitCode; |
1343 | }; |
1344 | |
1345 | /// Conversion from Error to LLVMErrorRef for C error bindings. |
1346 | inline LLVMErrorRef wrap(Error Err) { |
1347 | return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release()); |
1348 | } |
1349 | |
1350 | /// Conversion from LLVMErrorRef to Error for C error bindings. |
1351 | inline Error unwrap(LLVMErrorRef ErrRef) { |
1352 | return Error(std::unique_ptr<ErrorInfoBase>( |
1353 | reinterpret_cast<ErrorInfoBase *>(ErrRef))); |
1354 | } |
1355 | |
1356 | } // end namespace llvm |
1357 | |
1358 | #endif // LLVM_SUPPORT_ERROR_H |