File: | build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/llvm/lib/Bitcode/Reader/BitcodeReader.cpp |
Warning: | line 4054, column 5 Value stored to 'OpNum' is never read |
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/Bitcode/BitcodeCommon.h" |
24 | #include "llvm/Bitcode/LLVMBitCodes.h" |
25 | #include "llvm/Bitstream/BitstreamReader.h" |
26 | #include "llvm/Config/llvm-config.h" |
27 | #include "llvm/IR/Argument.h" |
28 | #include "llvm/IR/Attributes.h" |
29 | #include "llvm/IR/AutoUpgrade.h" |
30 | #include "llvm/IR/BasicBlock.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/GetElementPtrTypeIterator.h" |
43 | #include "llvm/IR/GlobalAlias.h" |
44 | #include "llvm/IR/GlobalIFunc.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/IntrinsicsAArch64.h" |
55 | #include "llvm/IR/IntrinsicsARM.h" |
56 | #include "llvm/IR/LLVMContext.h" |
57 | #include "llvm/IR/Metadata.h" |
58 | #include "llvm/IR/Module.h" |
59 | #include "llvm/IR/ModuleSummaryIndex.h" |
60 | #include "llvm/IR/Operator.h" |
61 | #include "llvm/IR/Type.h" |
62 | #include "llvm/IR/Value.h" |
63 | #include "llvm/IR/Verifier.h" |
64 | #include "llvm/Support/AtomicOrdering.h" |
65 | #include "llvm/Support/Casting.h" |
66 | #include "llvm/Support/CommandLine.h" |
67 | #include "llvm/Support/Compiler.h" |
68 | #include "llvm/Support/Debug.h" |
69 | #include "llvm/Support/Error.h" |
70 | #include "llvm/Support/ErrorHandling.h" |
71 | #include "llvm/Support/ErrorOr.h" |
72 | #include "llvm/Support/MathExtras.h" |
73 | #include "llvm/Support/MemoryBuffer.h" |
74 | #include "llvm/Support/raw_ostream.h" |
75 | #include <algorithm> |
76 | #include <cassert> |
77 | #include <cstddef> |
78 | #include <cstdint> |
79 | #include <deque> |
80 | #include <map> |
81 | #include <memory> |
82 | #include <set> |
83 | #include <string> |
84 | #include <system_error> |
85 | #include <tuple> |
86 | #include <utility> |
87 | #include <vector> |
88 | |
89 | using namespace llvm; |
90 | |
91 | static cl::opt<bool> PrintSummaryGUIDs( |
92 | "print-summary-global-ids", cl::init(false), cl::Hidden, |
93 | cl::desc( |
94 | "Print the global id for each value when reading the module summary")); |
95 | |
96 | static cl::opt<bool> ExpandConstantExprs( |
97 | "expand-constant-exprs", cl::Hidden, |
98 | cl::desc( |
99 | "Expand constant expressions to instructions for testing purposes")); |
100 | |
101 | namespace { |
102 | |
103 | enum { |
104 | SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex |
105 | }; |
106 | |
107 | } // end anonymous namespace |
108 | |
109 | static Error error(const Twine &Message) { |
110 | return make_error<StringError>( |
111 | Message, make_error_code(BitcodeError::CorruptedBitcode)); |
112 | } |
113 | |
114 | static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) { |
115 | if (!Stream.canSkipToPos(4)) |
116 | return createStringError(std::errc::illegal_byte_sequence, |
117 | "file too small to contain bitcode header"); |
118 | for (unsigned C : {'B', 'C'}) |
119 | if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { |
120 | if (Res.get() != C) |
121 | return createStringError(std::errc::illegal_byte_sequence, |
122 | "file doesn't start with bitcode header"); |
123 | } else |
124 | return Res.takeError(); |
125 | for (unsigned C : {0x0, 0xC, 0xE, 0xD}) |
126 | if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) { |
127 | if (Res.get() != C) |
128 | return createStringError(std::errc::illegal_byte_sequence, |
129 | "file doesn't start with bitcode header"); |
130 | } else |
131 | return Res.takeError(); |
132 | return Error::success(); |
133 | } |
134 | |
135 | static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) { |
136 | const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart(); |
137 | const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize(); |
138 | |
139 | if (Buffer.getBufferSize() & 3) |
140 | return error("Invalid bitcode signature"); |
141 | |
142 | // If we have a wrapper header, parse it and ignore the non-bc file contents. |
143 | // The magic number is 0x0B17C0DE stored in little endian. |
144 | if (isBitcodeWrapper(BufPtr, BufEnd)) |
145 | if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) |
146 | return error("Invalid bitcode wrapper header"); |
147 | |
148 | BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd)); |
149 | if (Error Err = hasInvalidBitcodeHeader(Stream)) |
150 | return std::move(Err); |
151 | |
152 | return std::move(Stream); |
153 | } |
154 | |
155 | /// Convert a string from a record into an std::string, return true on failure. |
156 | template <typename StrTy> |
157 | static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, |
158 | StrTy &Result) { |
159 | if (Idx > Record.size()) |
160 | return true; |
161 | |
162 | Result.append(Record.begin() + Idx, Record.end()); |
163 | return false; |
164 | } |
165 | |
166 | // Strip all the TBAA attachment for the module. |
167 | static void stripTBAA(Module *M) { |
168 | for (auto &F : *M) { |
169 | if (F.isMaterializable()) |
170 | continue; |
171 | for (auto &I : instructions(F)) |
172 | I.setMetadata(LLVMContext::MD_tbaa, nullptr); |
173 | } |
174 | } |
175 | |
176 | /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the |
177 | /// "epoch" encoded in the bitcode, and return the producer name if any. |
178 | static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) { |
179 | if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) |
180 | return std::move(Err); |
181 | |
182 | // Read all the records. |
183 | SmallVector<uint64_t, 64> Record; |
184 | |
185 | std::string ProducerIdentification; |
186 | |
187 | while (true) { |
188 | BitstreamEntry Entry; |
189 | if (Error E = Stream.advance().moveInto(Entry)) |
190 | return std::move(E); |
191 | |
192 | switch (Entry.Kind) { |
193 | default: |
194 | case BitstreamEntry::Error: |
195 | return error("Malformed block"); |
196 | case BitstreamEntry::EndBlock: |
197 | return ProducerIdentification; |
198 | case BitstreamEntry::Record: |
199 | // The interesting case. |
200 | break; |
201 | } |
202 | |
203 | // Read a record. |
204 | Record.clear(); |
205 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); |
206 | if (!MaybeBitCode) |
207 | return MaybeBitCode.takeError(); |
208 | switch (MaybeBitCode.get()) { |
209 | default: // Default behavior: reject |
210 | return error("Invalid value"); |
211 | case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N] |
212 | convertToString(Record, 0, ProducerIdentification); |
213 | break; |
214 | case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] |
215 | unsigned epoch = (unsigned)Record[0]; |
216 | if (epoch != bitc::BITCODE_CURRENT_EPOCH) { |
217 | return error( |
218 | Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + |
219 | "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); |
220 | } |
221 | } |
222 | } |
223 | } |
224 | } |
225 | |
226 | static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) { |
227 | // We expect a number of well-defined blocks, though we don't necessarily |
228 | // need to understand them all. |
229 | while (true) { |
230 | if (Stream.AtEndOfStream()) |
231 | return ""; |
232 | |
233 | BitstreamEntry Entry; |
234 | if (Error E = Stream.advance().moveInto(Entry)) |
235 | return std::move(E); |
236 | |
237 | switch (Entry.Kind) { |
238 | case BitstreamEntry::EndBlock: |
239 | case BitstreamEntry::Error: |
240 | return error("Malformed block"); |
241 | |
242 | case BitstreamEntry::SubBlock: |
243 | if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) |
244 | return readIdentificationBlock(Stream); |
245 | |
246 | // Ignore other sub-blocks. |
247 | if (Error Err = Stream.SkipBlock()) |
248 | return std::move(Err); |
249 | continue; |
250 | case BitstreamEntry::Record: |
251 | if (Error E = Stream.skipRecord(Entry.ID).takeError()) |
252 | return std::move(E); |
253 | continue; |
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 section name 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", "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 (Error E = Stream.advance().moveInto(Entry)) |
311 | return std::move(E); |
312 | |
313 | switch (Entry.Kind) { |
314 | case BitstreamEntry::Error: |
315 | return error("Malformed block"); |
316 | case BitstreamEntry::EndBlock: |
317 | return false; |
318 | |
319 | case BitstreamEntry::SubBlock: |
320 | if (Entry.ID == bitc::MODULE_BLOCK_ID) |
321 | return hasObjCCategoryInModule(Stream); |
322 | |
323 | // Ignore other sub-blocks. |
324 | if (Error Err = Stream.SkipBlock()) |
325 | return std::move(Err); |
326 | continue; |
327 | |
328 | case BitstreamEntry::Record: |
329 | if (Error E = Stream.skipRecord(Entry.ID).takeError()) |
330 | return std::move(E); |
331 | continue; |
332 | } |
333 | } |
334 | } |
335 | |
336 | static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) { |
337 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) |
338 | return std::move(Err); |
339 | |
340 | SmallVector<uint64_t, 64> Record; |
341 | |
342 | std::string Triple; |
343 | |
344 | // Read all the records for this module. |
345 | while (true) { |
346 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
347 | if (!MaybeEntry) |
348 | return MaybeEntry.takeError(); |
349 | BitstreamEntry Entry = MaybeEntry.get(); |
350 | |
351 | switch (Entry.Kind) { |
352 | case BitstreamEntry::SubBlock: // Handled for us already. |
353 | case BitstreamEntry::Error: |
354 | return error("Malformed block"); |
355 | case BitstreamEntry::EndBlock: |
356 | return Triple; |
357 | case BitstreamEntry::Record: |
358 | // The interesting case. |
359 | break; |
360 | } |
361 | |
362 | // Read a record. |
363 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
364 | if (!MaybeRecord) |
365 | return MaybeRecord.takeError(); |
366 | switch (MaybeRecord.get()) { |
367 | default: break; // Default behavior, ignore unknown content. |
368 | case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] |
369 | std::string S; |
370 | if (convertToString(Record, 0, S)) |
371 | return error("Invalid triple record"); |
372 | Triple = S; |
373 | break; |
374 | } |
375 | } |
376 | Record.clear(); |
377 | } |
378 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 378); |
379 | } |
380 | |
381 | static Expected<std::string> readTriple(BitstreamCursor &Stream) { |
382 | // We expect a number of well-defined blocks, though we don't necessarily |
383 | // need to understand them all. |
384 | while (true) { |
385 | Expected<BitstreamEntry> MaybeEntry = Stream.advance(); |
386 | if (!MaybeEntry) |
387 | return MaybeEntry.takeError(); |
388 | BitstreamEntry Entry = MaybeEntry.get(); |
389 | |
390 | switch (Entry.Kind) { |
391 | case BitstreamEntry::Error: |
392 | return error("Malformed block"); |
393 | case BitstreamEntry::EndBlock: |
394 | return ""; |
395 | |
396 | case BitstreamEntry::SubBlock: |
397 | if (Entry.ID == bitc::MODULE_BLOCK_ID) |
398 | return readModuleTriple(Stream); |
399 | |
400 | // Ignore other sub-blocks. |
401 | if (Error Err = Stream.SkipBlock()) |
402 | return std::move(Err); |
403 | continue; |
404 | |
405 | case BitstreamEntry::Record: |
406 | if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID)) |
407 | continue; |
408 | else |
409 | return Skipped.takeError(); |
410 | } |
411 | } |
412 | } |
413 | |
414 | namespace { |
415 | |
416 | class BitcodeReaderBase { |
417 | protected: |
418 | BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab) |
419 | : Stream(std::move(Stream)), Strtab(Strtab) { |
420 | this->Stream.setBlockInfo(&BlockInfo); |
421 | } |
422 | |
423 | BitstreamBlockInfo BlockInfo; |
424 | BitstreamCursor Stream; |
425 | StringRef Strtab; |
426 | |
427 | /// In version 2 of the bitcode we store names of global values and comdats in |
428 | /// a string table rather than in the VST. |
429 | bool UseStrtab = false; |
430 | |
431 | Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record); |
432 | |
433 | /// If this module uses a string table, pop the reference to the string table |
434 | /// and return the referenced string and the rest of the record. Otherwise |
435 | /// just return the record itself. |
436 | std::pair<StringRef, ArrayRef<uint64_t>> |
437 | readNameFromStrtab(ArrayRef<uint64_t> Record); |
438 | |
439 | Error readBlockInfo(); |
440 | |
441 | // Contains an arbitrary and optional string identifying the bitcode producer |
442 | std::string ProducerIdentification; |
443 | |
444 | Error error(const Twine &Message); |
445 | }; |
446 | |
447 | } // end anonymous namespace |
448 | |
449 | Error BitcodeReaderBase::error(const Twine &Message) { |
450 | std::string FullMsg = Message.str(); |
451 | if (!ProducerIdentification.empty()) |
452 | FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " + |
453 | LLVM_VERSION_STRING"16.0.0" "')"; |
454 | return ::error(FullMsg); |
455 | } |
456 | |
457 | Expected<unsigned> |
458 | BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) { |
459 | if (Record.empty()) |
460 | return error("Invalid version record"); |
461 | unsigned ModuleVersion = Record[0]; |
462 | if (ModuleVersion > 2) |
463 | return error("Invalid value"); |
464 | UseStrtab = ModuleVersion >= 2; |
465 | return ModuleVersion; |
466 | } |
467 | |
468 | std::pair<StringRef, ArrayRef<uint64_t>> |
469 | BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) { |
470 | if (!UseStrtab) |
471 | return {"", Record}; |
472 | // Invalid reference. Let the caller complain about the record being empty. |
473 | if (Record[0] + Record[1] > Strtab.size()) |
474 | return {"", {}}; |
475 | return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)}; |
476 | } |
477 | |
478 | namespace { |
479 | |
480 | /// This represents a constant expression or constant aggregate using a custom |
481 | /// structure internal to the bitcode reader. Later, this structure will be |
482 | /// expanded by materializeValue() either into a constant expression/aggregate, |
483 | /// or into an instruction sequence at the point of use. This allows us to |
484 | /// upgrade bitcode using constant expressions even if this kind of constant |
485 | /// expression is no longer supported. |
486 | class BitcodeConstant final : public Value, |
487 | TrailingObjects<BitcodeConstant, unsigned> { |
488 | friend TrailingObjects; |
489 | |
490 | // Value subclass ID: Pick largest possible value to avoid any clashes. |
491 | static constexpr uint8_t SubclassID = 255; |
492 | |
493 | public: |
494 | // Opcodes used for non-expressions. This includes constant aggregates |
495 | // (struct, array, vector) that might need expansion, as well as non-leaf |
496 | // constants that don't need expansion (no_cfi, dso_local, blockaddress), |
497 | // but still go through BitcodeConstant to avoid different uselist orders |
498 | // between the two cases. |
499 | static constexpr uint8_t ConstantStructOpcode = 255; |
500 | static constexpr uint8_t ConstantArrayOpcode = 254; |
501 | static constexpr uint8_t ConstantVectorOpcode = 253; |
502 | static constexpr uint8_t NoCFIOpcode = 252; |
503 | static constexpr uint8_t DSOLocalEquivalentOpcode = 251; |
504 | static constexpr uint8_t BlockAddressOpcode = 250; |
505 | static constexpr uint8_t FirstSpecialOpcode = BlockAddressOpcode; |
506 | |
507 | // Separate struct to make passing different number of parameters to |
508 | // BitcodeConstant::create() more convenient. |
509 | struct ExtraInfo { |
510 | uint8_t Opcode; |
511 | uint8_t Flags; |
512 | unsigned Extra; |
513 | Type *SrcElemTy; |
514 | |
515 | ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, unsigned Extra = 0, |
516 | Type *SrcElemTy = nullptr) |
517 | : Opcode(Opcode), Flags(Flags), Extra(Extra), SrcElemTy(SrcElemTy) {} |
518 | }; |
519 | |
520 | uint8_t Opcode; |
521 | uint8_t Flags; |
522 | unsigned NumOperands; |
523 | unsigned Extra; // GEP inrange index or blockaddress BB id. |
524 | Type *SrcElemTy; // GEP source element type. |
525 | |
526 | private: |
527 | BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs) |
528 | : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags), |
529 | NumOperands(OpIDs.size()), Extra(Info.Extra), |
530 | SrcElemTy(Info.SrcElemTy) { |
531 | std::uninitialized_copy(OpIDs.begin(), OpIDs.end(), |
532 | getTrailingObjects<unsigned>()); |
533 | } |
534 | |
535 | BitcodeConstant &operator=(const BitcodeConstant &) = delete; |
536 | |
537 | public: |
538 | static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty, |
539 | const ExtraInfo &Info, |
540 | ArrayRef<unsigned> OpIDs) { |
541 | void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()), |
542 | alignof(BitcodeConstant)); |
543 | return new (Mem) BitcodeConstant(Ty, Info, OpIDs); |
544 | } |
545 | |
546 | static bool classof(const Value *V) { return V->getValueID() == SubclassID; } |
547 | |
548 | ArrayRef<unsigned> getOperandIDs() const { |
549 | return makeArrayRef(getTrailingObjects<unsigned>(), NumOperands); |
550 | } |
551 | |
552 | Optional<unsigned> getInRangeIndex() const { |
553 | assert(Opcode == Instruction::GetElementPtr)(static_cast <bool> (Opcode == Instruction::GetElementPtr ) ? void (0) : __assert_fail ("Opcode == Instruction::GetElementPtr" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 553, __extension__ __PRETTY_FUNCTION__)); |
554 | if (Extra == (unsigned)-1) |
555 | return None; |
556 | return Extra; |
557 | } |
558 | |
559 | const char *getOpcodeName() const { |
560 | return Instruction::getOpcodeName(Opcode); |
561 | } |
562 | }; |
563 | |
564 | class BitcodeReader : public BitcodeReaderBase, public GVMaterializer { |
565 | LLVMContext &Context; |
566 | Module *TheModule = nullptr; |
567 | // Next offset to start scanning for lazy parsing of function bodies. |
568 | uint64_t NextUnreadBit = 0; |
569 | // Last function offset found in the VST. |
570 | uint64_t LastFunctionBlockBit = 0; |
571 | bool SeenValueSymbolTable = false; |
572 | uint64_t VSTOffset = 0; |
573 | |
574 | std::vector<std::string> SectionTable; |
575 | std::vector<std::string> GCTable; |
576 | |
577 | std::vector<Type *> TypeList; |
578 | /// Track type IDs of contained types. Order is the same as the contained |
579 | /// types of a Type*. This is used during upgrades of typed pointer IR in |
580 | /// opaque pointer mode. |
581 | DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs; |
582 | /// In some cases, we need to create a type ID for a type that was not |
583 | /// explicitly encoded in the bitcode, or we don't know about at the current |
584 | /// point. For example, a global may explicitly encode the value type ID, but |
585 | /// not have a type ID for the pointer to value type, for which we create a |
586 | /// virtual type ID instead. This map stores the new type ID that was created |
587 | /// for the given pair of Type and contained type ID. |
588 | DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs; |
589 | DenseMap<Function *, unsigned> FunctionTypeIDs; |
590 | /// Allocator for BitcodeConstants. This should come before ValueList, |
591 | /// because the ValueList might hold ValueHandles to these constants, so |
592 | /// ValueList must be destroyed before Alloc. |
593 | BumpPtrAllocator Alloc; |
594 | BitcodeReaderValueList ValueList; |
595 | Optional<MetadataLoader> MDLoader; |
596 | std::vector<Comdat *> ComdatList; |
597 | DenseSet<GlobalObject *> ImplicitComdatObjects; |
598 | SmallVector<Instruction *, 64> InstructionList; |
599 | |
600 | std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits; |
601 | std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits; |
602 | |
603 | struct FunctionOperandInfo { |
604 | Function *F; |
605 | unsigned PersonalityFn; |
606 | unsigned Prefix; |
607 | unsigned Prologue; |
608 | }; |
609 | std::vector<FunctionOperandInfo> FunctionOperands; |
610 | |
611 | /// The set of attributes by index. Index zero in the file is for null, and |
612 | /// is thus not represented here. As such all indices are off by one. |
613 | std::vector<AttributeList> MAttributes; |
614 | |
615 | /// The set of attribute groups. |
616 | std::map<unsigned, AttributeList> MAttributeGroups; |
617 | |
618 | /// While parsing a function body, this is a list of the basic blocks for the |
619 | /// function. |
620 | std::vector<BasicBlock*> FunctionBBs; |
621 | |
622 | // When reading the module header, this list is populated with functions that |
623 | // have bodies later in the file. |
624 | std::vector<Function*> FunctionsWithBodies; |
625 | |
626 | // When intrinsic functions are encountered which require upgrading they are |
627 | // stored here with their replacement function. |
628 | using UpdatedIntrinsicMap = DenseMap<Function *, Function *>; |
629 | UpdatedIntrinsicMap UpgradedIntrinsics; |
630 | // Intrinsics which were remangled because of types rename |
631 | UpdatedIntrinsicMap RemangledIntrinsics; |
632 | |
633 | // Several operations happen after the module header has been read, but |
634 | // before function bodies are processed. This keeps track of whether |
635 | // we've done this yet. |
636 | bool SeenFirstFunctionBody = false; |
637 | |
638 | /// When function bodies are initially scanned, this map contains info about |
639 | /// where to find deferred function body in the stream. |
640 | DenseMap<Function*, uint64_t> DeferredFunctionInfo; |
641 | |
642 | /// When Metadata block is initially scanned when parsing the module, we may |
643 | /// choose to defer parsing of the metadata. This vector contains info about |
644 | /// which Metadata blocks are deferred. |
645 | std::vector<uint64_t> DeferredMetadataInfo; |
646 | |
647 | /// These are basic blocks forward-referenced by block addresses. They are |
648 | /// inserted lazily into functions when they're loaded. The basic block ID is |
649 | /// its index into the vector. |
650 | DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; |
651 | std::deque<Function *> BasicBlockFwdRefQueue; |
652 | |
653 | /// These are Functions that contain BlockAddresses which refer a different |
654 | /// Function. When parsing the different Function, queue Functions that refer |
655 | /// to the different Function. Those Functions must be materialized in order |
656 | /// to resolve their BlockAddress constants before the different Function |
657 | /// gets moved into another Module. |
658 | std::vector<Function *> BackwardRefFunctions; |
659 | |
660 | /// Indicates that we are using a new encoding for instruction operands where |
661 | /// most operands in the current FUNCTION_BLOCK are encoded relative to the |
662 | /// instruction number, for a more compact encoding. Some instruction |
663 | /// operands are not relative to the instruction ID: basic block numbers, and |
664 | /// types. Once the old style function blocks have been phased out, we would |
665 | /// not need this flag. |
666 | bool UseRelativeIDs = false; |
667 | |
668 | /// True if all functions will be materialized, negating the need to process |
669 | /// (e.g.) blockaddress forward references. |
670 | bool WillMaterializeAllForwardRefs = false; |
671 | |
672 | bool StripDebugInfo = false; |
673 | TBAAVerifier TBAAVerifyHelper; |
674 | |
675 | std::vector<std::string> BundleTags; |
676 | SmallVector<SyncScope::ID, 8> SSIDs; |
677 | |
678 | public: |
679 | BitcodeReader(BitstreamCursor Stream, StringRef Strtab, |
680 | StringRef ProducerIdentification, LLVMContext &Context); |
681 | |
682 | Error materializeForwardReferencedFunctions(); |
683 | |
684 | Error materialize(GlobalValue *GV) override; |
685 | Error materializeModule() override; |
686 | std::vector<StructType *> getIdentifiedStructTypes() const override; |
687 | |
688 | /// Main interface to parsing a bitcode buffer. |
689 | /// \returns true if an error occurred. |
690 | Error parseBitcodeInto( |
691 | Module *M, bool ShouldLazyLoadMetadata, bool IsImporting, |
692 | DataLayoutCallbackTy DataLayoutCallback); |
693 | |
694 | static uint64_t decodeSignRotatedValue(uint64_t V); |
695 | |
696 | /// Materialize any deferred Metadata block. |
697 | Error materializeMetadata() override; |
698 | |
699 | void setStripDebugInfo() override; |
700 | |
701 | private: |
702 | std::vector<StructType *> IdentifiedStructTypes; |
703 | StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); |
704 | StructType *createIdentifiedStructType(LLVMContext &Context); |
705 | |
706 | static constexpr unsigned InvalidTypeID = ~0u; |
707 | |
708 | Type *getTypeByID(unsigned ID); |
709 | Type *getPtrElementTypeByID(unsigned ID); |
710 | unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0); |
711 | unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {}); |
712 | |
713 | Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB); |
714 | Expected<Constant *> getValueForInitializer(unsigned ID); |
715 | |
716 | Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID, |
717 | BasicBlock *ConstExprInsertBB) { |
718 | if (Ty && Ty->isMetadataTy()) |
719 | return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); |
720 | return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB); |
721 | } |
722 | |
723 | Metadata *getFnMetadataByID(unsigned ID) { |
724 | return MDLoader->getMetadataFwdRefOrLoad(ID); |
725 | } |
726 | |
727 | BasicBlock *getBasicBlock(unsigned ID) const { |
728 | if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID |
729 | return FunctionBBs[ID]; |
730 | } |
731 | |
732 | AttributeList getAttributes(unsigned i) const { |
733 | if (i-1 < MAttributes.size()) |
734 | return MAttributes[i-1]; |
735 | return AttributeList(); |
736 | } |
737 | |
738 | /// Read a value/type pair out of the specified record from slot 'Slot'. |
739 | /// Increment Slot past the number of slots used in the record. Return true on |
740 | /// failure. |
741 | bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, |
742 | unsigned InstNum, Value *&ResVal, unsigned &TypeID, |
743 | BasicBlock *ConstExprInsertBB) { |
744 | if (Slot == Record.size()) return true; |
745 | unsigned ValNo = (unsigned)Record[Slot++]; |
746 | // Adjust the ValNo, if it was encoded relative to the InstNum. |
747 | if (UseRelativeIDs) |
748 | ValNo = InstNum - ValNo; |
749 | if (ValNo < InstNum) { |
750 | // If this is not a forward reference, just return the value we already |
751 | // have. |
752 | TypeID = ValueList.getTypeID(ValNo); |
753 | ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB); |
754 | assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) &&(static_cast <bool> ((!ResVal || ResVal->getType() == getTypeByID(TypeID)) && "Incorrect type ID stored for value" ) ? void (0) : __assert_fail ("(!ResVal || ResVal->getType() == getTypeByID(TypeID)) && \"Incorrect type ID stored for value\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 755, __extension__ __PRETTY_FUNCTION__)) |
755 | "Incorrect type ID stored for value")(static_cast <bool> ((!ResVal || ResVal->getType() == getTypeByID(TypeID)) && "Incorrect type ID stored for value" ) ? void (0) : __assert_fail ("(!ResVal || ResVal->getType() == getTypeByID(TypeID)) && \"Incorrect type ID stored for value\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 755, __extension__ __PRETTY_FUNCTION__)); |
756 | return ResVal == nullptr; |
757 | } |
758 | if (Slot == Record.size()) |
759 | return true; |
760 | |
761 | TypeID = (unsigned)Record[Slot++]; |
762 | ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID, |
763 | ConstExprInsertBB); |
764 | return ResVal == nullptr; |
765 | } |
766 | |
767 | /// Read a value out of the specified record from slot 'Slot'. Increment Slot |
768 | /// past the number of slots used by the value in the record. Return true if |
769 | /// there is an error. |
770 | bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, |
771 | unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal, |
772 | BasicBlock *ConstExprInsertBB) { |
773 | if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB)) |
774 | return true; |
775 | // All values currently take a single record slot. |
776 | ++Slot; |
777 | return false; |
778 | } |
779 | |
780 | /// Like popValue, but does not increment the Slot number. |
781 | bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, |
782 | unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal, |
783 | BasicBlock *ConstExprInsertBB) { |
784 | ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB); |
785 | return ResVal == nullptr; |
786 | } |
787 | |
788 | /// Version of getValue that returns ResVal directly, or 0 if there is an |
789 | /// error. |
790 | Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, |
791 | unsigned InstNum, Type *Ty, unsigned TyID, |
792 | BasicBlock *ConstExprInsertBB) { |
793 | if (Slot == Record.size()) return nullptr; |
794 | unsigned ValNo = (unsigned)Record[Slot]; |
795 | // Adjust the ValNo, if it was encoded relative to the InstNum. |
796 | if (UseRelativeIDs) |
797 | ValNo = InstNum - ValNo; |
798 | return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB); |
799 | } |
800 | |
801 | /// Like getValue, but decodes signed VBRs. |
802 | Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, |
803 | unsigned InstNum, Type *Ty, unsigned TyID, |
804 | BasicBlock *ConstExprInsertBB) { |
805 | if (Slot == Record.size()) return nullptr; |
806 | unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); |
807 | // Adjust the ValNo, if it was encoded relative to the InstNum. |
808 | if (UseRelativeIDs) |
809 | ValNo = InstNum - ValNo; |
810 | return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB); |
811 | } |
812 | |
813 | /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the |
814 | /// corresponding argument's pointee type. Also upgrades intrinsics that now |
815 | /// require an elementtype attribute. |
816 | Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys); |
817 | |
818 | /// Converts alignment exponent (i.e. power of two (or zero)) to the |
819 | /// corresponding alignment to use. If alignment is too large, returns |
820 | /// a corresponding error code. |
821 | Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment); |
822 | Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); |
823 | Error parseModule( |
824 | uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false, |
825 | DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; }); |
826 | |
827 | Error parseComdatRecord(ArrayRef<uint64_t> Record); |
828 | Error parseGlobalVarRecord(ArrayRef<uint64_t> Record); |
829 | Error parseFunctionRecord(ArrayRef<uint64_t> Record); |
830 | Error parseGlobalIndirectSymbolRecord(unsigned BitCode, |
831 | ArrayRef<uint64_t> Record); |
832 | |
833 | Error parseAttributeBlock(); |
834 | Error parseAttributeGroupBlock(); |
835 | Error parseTypeTable(); |
836 | Error parseTypeTableBody(); |
837 | Error parseOperandBundleTags(); |
838 | Error parseSyncScopeNames(); |
839 | |
840 | Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, |
841 | unsigned NameIndex, Triple &TT); |
842 | void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F, |
843 | ArrayRef<uint64_t> Record); |
844 | Error parseValueSymbolTable(uint64_t Offset = 0); |
845 | Error parseGlobalValueSymbolTable(); |
846 | Error parseConstants(); |
847 | Error rememberAndSkipFunctionBodies(); |
848 | Error rememberAndSkipFunctionBody(); |
849 | /// Save the positions of the Metadata blocks and skip parsing the blocks. |
850 | Error rememberAndSkipMetadata(); |
851 | Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType); |
852 | Error parseFunctionBody(Function *F); |
853 | Error globalCleanup(); |
854 | Error resolveGlobalAndIndirectSymbolInits(); |
855 | Error parseUseLists(); |
856 | Error findFunctionInStream( |
857 | Function *F, |
858 | DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); |
859 | |
860 | SyncScope::ID getDecodedSyncScopeID(unsigned Val); |
861 | }; |
862 | |
863 | /// Class to manage reading and parsing function summary index bitcode |
864 | /// files/sections. |
865 | class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase { |
866 | /// The module index built during parsing. |
867 | ModuleSummaryIndex &TheIndex; |
868 | |
869 | /// Indicates whether we have encountered a global value summary section |
870 | /// yet during parsing. |
871 | bool SeenGlobalValSummary = false; |
872 | |
873 | /// Indicates whether we have already parsed the VST, used for error checking. |
874 | bool SeenValueSymbolTable = false; |
875 | |
876 | /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. |
877 | /// Used to enable on-demand parsing of the VST. |
878 | uint64_t VSTOffset = 0; |
879 | |
880 | // Map to save ValueId to ValueInfo association that was recorded in the |
881 | // ValueSymbolTable. It is used after the VST is parsed to convert |
882 | // call graph edges read from the function summary from referencing |
883 | // callees by their ValueId to using the ValueInfo instead, which is how |
884 | // they are recorded in the summary index being built. |
885 | // We save a GUID which refers to the same global as the ValueInfo, but |
886 | // ignoring the linkage, i.e. for values other than local linkage they are |
887 | // identical. |
888 | DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>> |
889 | ValueIdToValueInfoMap; |
890 | |
891 | /// Map populated during module path string table parsing, from the |
892 | /// module ID to a string reference owned by the index's module |
893 | /// path string table, used to correlate with combined index |
894 | /// summary records. |
895 | DenseMap<uint64_t, StringRef> ModuleIdMap; |
896 | |
897 | /// Original source file name recorded in a bitcode record. |
898 | std::string SourceFileName; |
899 | |
900 | /// The string identifier given to this module by the client, normally the |
901 | /// path to the bitcode file. |
902 | StringRef ModulePath; |
903 | |
904 | /// For per-module summary indexes, the unique numerical identifier given to |
905 | /// this module by the client. |
906 | unsigned ModuleId; |
907 | |
908 | public: |
909 | ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab, |
910 | ModuleSummaryIndex &TheIndex, |
911 | StringRef ModulePath, unsigned ModuleId); |
912 | |
913 | Error parseModule(); |
914 | |
915 | private: |
916 | void setValueGUID(uint64_t ValueID, StringRef ValueName, |
917 | GlobalValue::LinkageTypes Linkage, |
918 | StringRef SourceFileName); |
919 | Error parseValueSymbolTable( |
920 | uint64_t Offset, |
921 | DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); |
922 | std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record); |
923 | std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record, |
924 | bool IsOldProfileFormat, |
925 | bool HasProfile, |
926 | bool HasRelBF); |
927 | Error parseEntireSummary(unsigned ID); |
928 | Error parseModuleStringTable(); |
929 | void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record); |
930 | void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot, |
931 | TypeIdCompatibleVtableInfo &TypeId); |
932 | std::vector<FunctionSummary::ParamAccess> |
933 | parseParamAccesses(ArrayRef<uint64_t> Record); |
934 | |
935 | std::pair<ValueInfo, GlobalValue::GUID> |
936 | getValueInfoFromValueId(unsigned ValueId); |
937 | |
938 | void addThisModule(); |
939 | ModuleSummaryIndex::ModuleInfo *getThisModule(); |
940 | }; |
941 | |
942 | } // end anonymous namespace |
943 | |
944 | std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, |
945 | Error Err) { |
946 | if (Err) { |
947 | std::error_code EC; |
948 | handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { |
949 | EC = EIB.convertToErrorCode(); |
950 | Ctx.emitError(EIB.message()); |
951 | }); |
952 | return EC; |
953 | } |
954 | return std::error_code(); |
955 | } |
956 | |
957 | BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab, |
958 | StringRef ProducerIdentification, |
959 | LLVMContext &Context) |
960 | : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context), |
961 | ValueList(this->Stream.SizeInBytes(), |
962 | [this](unsigned ValID, BasicBlock *InsertBB) { |
963 | return materializeValue(ValID, InsertBB); |
964 | }) { |
965 | this->ProducerIdentification = std::string(ProducerIdentification); |
966 | } |
967 | |
968 | Error BitcodeReader::materializeForwardReferencedFunctions() { |
969 | if (WillMaterializeAllForwardRefs) |
970 | return Error::success(); |
971 | |
972 | // Prevent recursion. |
973 | WillMaterializeAllForwardRefs = true; |
974 | |
975 | while (!BasicBlockFwdRefQueue.empty()) { |
976 | Function *F = BasicBlockFwdRefQueue.front(); |
977 | BasicBlockFwdRefQueue.pop_front(); |
978 | assert(F && "Expected valid function")(static_cast <bool> (F && "Expected valid function" ) ? void (0) : __assert_fail ("F && \"Expected valid function\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 978, __extension__ __PRETTY_FUNCTION__)); |
979 | if (!BasicBlockFwdRefs.count(F)) |
980 | // Already materialized. |
981 | continue; |
982 | |
983 | // Check for a function that isn't materializable to prevent an infinite |
984 | // loop. When parsing a blockaddress stored in a global variable, there |
985 | // isn't a trivial way to check if a function will have a body without a |
986 | // linear search through FunctionsWithBodies, so just check it here. |
987 | if (!F->isMaterializable()) |
988 | return error("Never resolved function from blockaddress"); |
989 | |
990 | // Try to materialize F. |
991 | if (Error Err = materialize(F)) |
992 | return Err; |
993 | } |
994 | assert(BasicBlockFwdRefs.empty() && "Function missing from queue")(static_cast <bool> (BasicBlockFwdRefs.empty() && "Function missing from queue") ? void (0) : __assert_fail ("BasicBlockFwdRefs.empty() && \"Function missing from queue\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 994, __extension__ __PRETTY_FUNCTION__)); |
995 | |
996 | for (Function *F : BackwardRefFunctions) |
997 | if (Error Err = materialize(F)) |
998 | return Err; |
999 | BackwardRefFunctions.clear(); |
1000 | |
1001 | // Reset state. |
1002 | WillMaterializeAllForwardRefs = false; |
1003 | return Error::success(); |
1004 | } |
1005 | |
1006 | //===----------------------------------------------------------------------===// |
1007 | // Helper functions to implement forward reference resolution, etc. |
1008 | //===----------------------------------------------------------------------===// |
1009 | |
1010 | static bool hasImplicitComdat(size_t Val) { |
1011 | switch (Val) { |
1012 | default: |
1013 | return false; |
1014 | case 1: // Old WeakAnyLinkage |
1015 | case 4: // Old LinkOnceAnyLinkage |
1016 | case 10: // Old WeakODRLinkage |
1017 | case 11: // Old LinkOnceODRLinkage |
1018 | return true; |
1019 | } |
1020 | } |
1021 | |
1022 | static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { |
1023 | switch (Val) { |
1024 | default: // Map unknown/new linkages to external |
1025 | case 0: |
1026 | return GlobalValue::ExternalLinkage; |
1027 | case 2: |
1028 | return GlobalValue::AppendingLinkage; |
1029 | case 3: |
1030 | return GlobalValue::InternalLinkage; |
1031 | case 5: |
1032 | return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage |
1033 | case 6: |
1034 | return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage |
1035 | case 7: |
1036 | return GlobalValue::ExternalWeakLinkage; |
1037 | case 8: |
1038 | return GlobalValue::CommonLinkage; |
1039 | case 9: |
1040 | return GlobalValue::PrivateLinkage; |
1041 | case 12: |
1042 | return GlobalValue::AvailableExternallyLinkage; |
1043 | case 13: |
1044 | return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage |
1045 | case 14: |
1046 | return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage |
1047 | case 15: |
1048 | return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage |
1049 | case 1: // Old value with implicit comdat. |
1050 | case 16: |
1051 | return GlobalValue::WeakAnyLinkage; |
1052 | case 10: // Old value with implicit comdat. |
1053 | case 17: |
1054 | return GlobalValue::WeakODRLinkage; |
1055 | case 4: // Old value with implicit comdat. |
1056 | case 18: |
1057 | return GlobalValue::LinkOnceAnyLinkage; |
1058 | case 11: // Old value with implicit comdat. |
1059 | case 19: |
1060 | return GlobalValue::LinkOnceODRLinkage; |
1061 | } |
1062 | } |
1063 | |
1064 | static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) { |
1065 | FunctionSummary::FFlags Flags; |
1066 | Flags.ReadNone = RawFlags & 0x1; |
1067 | Flags.ReadOnly = (RawFlags >> 1) & 0x1; |
1068 | Flags.NoRecurse = (RawFlags >> 2) & 0x1; |
1069 | Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1; |
1070 | Flags.NoInline = (RawFlags >> 4) & 0x1; |
1071 | Flags.AlwaysInline = (RawFlags >> 5) & 0x1; |
1072 | Flags.NoUnwind = (RawFlags >> 6) & 0x1; |
1073 | Flags.MayThrow = (RawFlags >> 7) & 0x1; |
1074 | Flags.HasUnknownCall = (RawFlags >> 8) & 0x1; |
1075 | Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1; |
1076 | return Flags; |
1077 | } |
1078 | |
1079 | // Decode the flags for GlobalValue in the summary. The bits for each attribute: |
1080 | // |
1081 | // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7, |
1082 | // visibility: [8, 10). |
1083 | static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, |
1084 | uint64_t Version) { |
1085 | // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage |
1086 | // like getDecodedLinkage() above. Any future change to the linkage enum and |
1087 | // to getDecodedLinkage() will need to be taken into account here as above. |
1088 | auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits |
1089 | auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits |
1090 | RawFlags = RawFlags >> 4; |
1091 | bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3; |
1092 | // The Live flag wasn't introduced until version 3. For dead stripping |
1093 | // to work correctly on earlier versions, we must conservatively treat all |
1094 | // values as live. |
1095 | bool Live = (RawFlags & 0x2) || Version < 3; |
1096 | bool Local = (RawFlags & 0x4); |
1097 | bool AutoHide = (RawFlags & 0x8); |
1098 | |
1099 | return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport, |
1100 | Live, Local, AutoHide); |
1101 | } |
1102 | |
1103 | // Decode the flags for GlobalVariable in the summary |
1104 | static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) { |
1105 | return GlobalVarSummary::GVarFlags( |
1106 | (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false, |
1107 | (RawFlags & 0x4) ? true : false, |
1108 | (GlobalObject::VCallVisibility)(RawFlags >> 3)); |
1109 | } |
1110 | |
1111 | static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { |
1112 | switch (Val) { |
1113 | default: // Map unknown visibilities to default. |
1114 | case 0: return GlobalValue::DefaultVisibility; |
1115 | case 1: return GlobalValue::HiddenVisibility; |
1116 | case 2: return GlobalValue::ProtectedVisibility; |
1117 | } |
1118 | } |
1119 | |
1120 | static GlobalValue::DLLStorageClassTypes |
1121 | getDecodedDLLStorageClass(unsigned Val) { |
1122 | switch (Val) { |
1123 | default: // Map unknown values to default. |
1124 | case 0: return GlobalValue::DefaultStorageClass; |
1125 | case 1: return GlobalValue::DLLImportStorageClass; |
1126 | case 2: return GlobalValue::DLLExportStorageClass; |
1127 | } |
1128 | } |
1129 | |
1130 | static bool getDecodedDSOLocal(unsigned Val) { |
1131 | switch(Val) { |
1132 | default: // Map unknown values to preemptable. |
1133 | case 0: return false; |
1134 | case 1: return true; |
1135 | } |
1136 | } |
1137 | |
1138 | static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { |
1139 | switch (Val) { |
1140 | case 0: return GlobalVariable::NotThreadLocal; |
1141 | default: // Map unknown non-zero value to general dynamic. |
1142 | case 1: return GlobalVariable::GeneralDynamicTLSModel; |
1143 | case 2: return GlobalVariable::LocalDynamicTLSModel; |
1144 | case 3: return GlobalVariable::InitialExecTLSModel; |
1145 | case 4: return GlobalVariable::LocalExecTLSModel; |
1146 | } |
1147 | } |
1148 | |
1149 | static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { |
1150 | switch (Val) { |
1151 | default: // Map unknown to UnnamedAddr::None. |
1152 | case 0: return GlobalVariable::UnnamedAddr::None; |
1153 | case 1: return GlobalVariable::UnnamedAddr::Global; |
1154 | case 2: return GlobalVariable::UnnamedAddr::Local; |
1155 | } |
1156 | } |
1157 | |
1158 | static int getDecodedCastOpcode(unsigned Val) { |
1159 | switch (Val) { |
1160 | default: return -1; |
1161 | case bitc::CAST_TRUNC : return Instruction::Trunc; |
1162 | case bitc::CAST_ZEXT : return Instruction::ZExt; |
1163 | case bitc::CAST_SEXT : return Instruction::SExt; |
1164 | case bitc::CAST_FPTOUI : return Instruction::FPToUI; |
1165 | case bitc::CAST_FPTOSI : return Instruction::FPToSI; |
1166 | case bitc::CAST_UITOFP : return Instruction::UIToFP; |
1167 | case bitc::CAST_SITOFP : return Instruction::SIToFP; |
1168 | case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; |
1169 | case bitc::CAST_FPEXT : return Instruction::FPExt; |
1170 | case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; |
1171 | case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; |
1172 | case bitc::CAST_BITCAST : return Instruction::BitCast; |
1173 | case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; |
1174 | } |
1175 | } |
1176 | |
1177 | static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) { |
1178 | bool IsFP = Ty->isFPOrFPVectorTy(); |
1179 | // UnOps are only valid for int/fp or vector of int/fp types |
1180 | if (!IsFP && !Ty->isIntOrIntVectorTy()) |
1181 | return -1; |
1182 | |
1183 | switch (Val) { |
1184 | default: |
1185 | return -1; |
1186 | case bitc::UNOP_FNEG: |
1187 | return IsFP ? Instruction::FNeg : -1; |
1188 | } |
1189 | } |
1190 | |
1191 | static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { |
1192 | bool IsFP = Ty->isFPOrFPVectorTy(); |
1193 | // BinOps are only valid for int/fp or vector of int/fp types |
1194 | if (!IsFP && !Ty->isIntOrIntVectorTy()) |
1195 | return -1; |
1196 | |
1197 | switch (Val) { |
1198 | default: |
1199 | return -1; |
1200 | case bitc::BINOP_ADD: |
1201 | return IsFP ? Instruction::FAdd : Instruction::Add; |
1202 | case bitc::BINOP_SUB: |
1203 | return IsFP ? Instruction::FSub : Instruction::Sub; |
1204 | case bitc::BINOP_MUL: |
1205 | return IsFP ? Instruction::FMul : Instruction::Mul; |
1206 | case bitc::BINOP_UDIV: |
1207 | return IsFP ? -1 : Instruction::UDiv; |
1208 | case bitc::BINOP_SDIV: |
1209 | return IsFP ? Instruction::FDiv : Instruction::SDiv; |
1210 | case bitc::BINOP_UREM: |
1211 | return IsFP ? -1 : Instruction::URem; |
1212 | case bitc::BINOP_SREM: |
1213 | return IsFP ? Instruction::FRem : Instruction::SRem; |
1214 | case bitc::BINOP_SHL: |
1215 | return IsFP ? -1 : Instruction::Shl; |
1216 | case bitc::BINOP_LSHR: |
1217 | return IsFP ? -1 : Instruction::LShr; |
1218 | case bitc::BINOP_ASHR: |
1219 | return IsFP ? -1 : Instruction::AShr; |
1220 | case bitc::BINOP_AND: |
1221 | return IsFP ? -1 : Instruction::And; |
1222 | case bitc::BINOP_OR: |
1223 | return IsFP ? -1 : Instruction::Or; |
1224 | case bitc::BINOP_XOR: |
1225 | return IsFP ? -1 : Instruction::Xor; |
1226 | } |
1227 | } |
1228 | |
1229 | static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { |
1230 | switch (Val) { |
1231 | default: return AtomicRMWInst::BAD_BINOP; |
1232 | case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; |
1233 | case bitc::RMW_ADD: return AtomicRMWInst::Add; |
1234 | case bitc::RMW_SUB: return AtomicRMWInst::Sub; |
1235 | case bitc::RMW_AND: return AtomicRMWInst::And; |
1236 | case bitc::RMW_NAND: return AtomicRMWInst::Nand; |
1237 | case bitc::RMW_OR: return AtomicRMWInst::Or; |
1238 | case bitc::RMW_XOR: return AtomicRMWInst::Xor; |
1239 | case bitc::RMW_MAX: return AtomicRMWInst::Max; |
1240 | case bitc::RMW_MIN: return AtomicRMWInst::Min; |
1241 | case bitc::RMW_UMAX: return AtomicRMWInst::UMax; |
1242 | case bitc::RMW_UMIN: return AtomicRMWInst::UMin; |
1243 | case bitc::RMW_FADD: return AtomicRMWInst::FAdd; |
1244 | case bitc::RMW_FSUB: return AtomicRMWInst::FSub; |
1245 | case bitc::RMW_FMAX: return AtomicRMWInst::FMax; |
1246 | case bitc::RMW_FMIN: return AtomicRMWInst::FMin; |
1247 | } |
1248 | } |
1249 | |
1250 | static AtomicOrdering getDecodedOrdering(unsigned Val) { |
1251 | switch (Val) { |
1252 | case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; |
1253 | case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; |
1254 | case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; |
1255 | case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; |
1256 | case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; |
1257 | case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; |
1258 | default: // Map unknown orderings to sequentially-consistent. |
1259 | case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; |
1260 | } |
1261 | } |
1262 | |
1263 | static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { |
1264 | switch (Val) { |
1265 | default: // Map unknown selection kinds to any. |
1266 | case bitc::COMDAT_SELECTION_KIND_ANY: |
1267 | return Comdat::Any; |
1268 | case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: |
1269 | return Comdat::ExactMatch; |
1270 | case bitc::COMDAT_SELECTION_KIND_LARGEST: |
1271 | return Comdat::Largest; |
1272 | case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: |
1273 | return Comdat::NoDeduplicate; |
1274 | case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: |
1275 | return Comdat::SameSize; |
1276 | } |
1277 | } |
1278 | |
1279 | static FastMathFlags getDecodedFastMathFlags(unsigned Val) { |
1280 | FastMathFlags FMF; |
1281 | if (0 != (Val & bitc::UnsafeAlgebra)) |
1282 | FMF.setFast(); |
1283 | if (0 != (Val & bitc::AllowReassoc)) |
1284 | FMF.setAllowReassoc(); |
1285 | if (0 != (Val & bitc::NoNaNs)) |
1286 | FMF.setNoNaNs(); |
1287 | if (0 != (Val & bitc::NoInfs)) |
1288 | FMF.setNoInfs(); |
1289 | if (0 != (Val & bitc::NoSignedZeros)) |
1290 | FMF.setNoSignedZeros(); |
1291 | if (0 != (Val & bitc::AllowReciprocal)) |
1292 | FMF.setAllowReciprocal(); |
1293 | if (0 != (Val & bitc::AllowContract)) |
1294 | FMF.setAllowContract(true); |
1295 | if (0 != (Val & bitc::ApproxFunc)) |
1296 | FMF.setApproxFunc(); |
1297 | return FMF; |
1298 | } |
1299 | |
1300 | static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { |
1301 | switch (Val) { |
1302 | case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; |
1303 | case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; |
1304 | } |
1305 | } |
1306 | |
1307 | Type *BitcodeReader::getTypeByID(unsigned ID) { |
1308 | // The type table size is always specified correctly. |
1309 | if (ID >= TypeList.size()) |
1310 | return nullptr; |
1311 | |
1312 | if (Type *Ty = TypeList[ID]) |
1313 | return Ty; |
1314 | |
1315 | // If we have a forward reference, the only possible case is when it is to a |
1316 | // named struct. Just create a placeholder for now. |
1317 | return TypeList[ID] = createIdentifiedStructType(Context); |
1318 | } |
1319 | |
1320 | unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) { |
1321 | auto It = ContainedTypeIDs.find(ID); |
1322 | if (It == ContainedTypeIDs.end()) |
1323 | return InvalidTypeID; |
1324 | |
1325 | if (Idx >= It->second.size()) |
1326 | return InvalidTypeID; |
1327 | |
1328 | return It->second[Idx]; |
1329 | } |
1330 | |
1331 | Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) { |
1332 | if (ID >= TypeList.size()) |
1333 | return nullptr; |
1334 | |
1335 | Type *Ty = TypeList[ID]; |
1336 | if (!Ty->isPointerTy()) |
1337 | return nullptr; |
1338 | |
1339 | Type *ElemTy = getTypeByID(getContainedTypeID(ID, 0)); |
1340 | if (!ElemTy) |
1341 | return nullptr; |
1342 | |
1343 | assert(cast<PointerType>(Ty)->isOpaqueOrPointeeTypeMatches(ElemTy) &&(static_cast <bool> (cast<PointerType>(Ty)->isOpaqueOrPointeeTypeMatches (ElemTy) && "Incorrect element type") ? void (0) : __assert_fail ("cast<PointerType>(Ty)->isOpaqueOrPointeeTypeMatches(ElemTy) && \"Incorrect element type\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1344, __extension__ __PRETTY_FUNCTION__)) |
1344 | "Incorrect element type")(static_cast <bool> (cast<PointerType>(Ty)->isOpaqueOrPointeeTypeMatches (ElemTy) && "Incorrect element type") ? void (0) : __assert_fail ("cast<PointerType>(Ty)->isOpaqueOrPointeeTypeMatches(ElemTy) && \"Incorrect element type\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1344, __extension__ __PRETTY_FUNCTION__)); |
1345 | return ElemTy; |
1346 | } |
1347 | |
1348 | unsigned BitcodeReader::getVirtualTypeID(Type *Ty, |
1349 | ArrayRef<unsigned> ChildTypeIDs) { |
1350 | unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0]; |
1351 | auto CacheKey = std::make_pair(Ty, ChildTypeID); |
1352 | auto It = VirtualTypeIDs.find(CacheKey); |
1353 | if (It != VirtualTypeIDs.end()) { |
1354 | // The cmpxchg return value is the only place we need more than one |
1355 | // contained type ID, however the second one will always be the same (i1), |
1356 | // so we don't need to include it in the cache key. This asserts that the |
1357 | // contained types are indeed as expected and there are no collisions. |
1358 | assert((ChildTypeIDs.empty() ||(static_cast <bool> ((ChildTypeIDs.empty() || ContainedTypeIDs [It->second] == ChildTypeIDs) && "Incorrect cached contained type IDs" ) ? void (0) : __assert_fail ("(ChildTypeIDs.empty() || ContainedTypeIDs[It->second] == ChildTypeIDs) && \"Incorrect cached contained type IDs\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1360, __extension__ __PRETTY_FUNCTION__)) |
1359 | ContainedTypeIDs[It->second] == ChildTypeIDs) &&(static_cast <bool> ((ChildTypeIDs.empty() || ContainedTypeIDs [It->second] == ChildTypeIDs) && "Incorrect cached contained type IDs" ) ? void (0) : __assert_fail ("(ChildTypeIDs.empty() || ContainedTypeIDs[It->second] == ChildTypeIDs) && \"Incorrect cached contained type IDs\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1360, __extension__ __PRETTY_FUNCTION__)) |
1360 | "Incorrect cached contained type IDs")(static_cast <bool> ((ChildTypeIDs.empty() || ContainedTypeIDs [It->second] == ChildTypeIDs) && "Incorrect cached contained type IDs" ) ? void (0) : __assert_fail ("(ChildTypeIDs.empty() || ContainedTypeIDs[It->second] == ChildTypeIDs) && \"Incorrect cached contained type IDs\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1360, __extension__ __PRETTY_FUNCTION__)); |
1361 | return It->second; |
1362 | } |
1363 | |
1364 | #ifndef NDEBUG |
1365 | if (!Ty->isOpaquePointerTy()) { |
1366 | assert(Ty->getNumContainedTypes() == ChildTypeIDs.size() &&(static_cast <bool> (Ty->getNumContainedTypes() == ChildTypeIDs .size() && "Wrong number of contained types") ? void ( 0) : __assert_fail ("Ty->getNumContainedTypes() == ChildTypeIDs.size() && \"Wrong number of contained types\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1367, __extension__ __PRETTY_FUNCTION__)) |
1367 | "Wrong number of contained types")(static_cast <bool> (Ty->getNumContainedTypes() == ChildTypeIDs .size() && "Wrong number of contained types") ? void ( 0) : __assert_fail ("Ty->getNumContainedTypes() == ChildTypeIDs.size() && \"Wrong number of contained types\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1367, __extension__ __PRETTY_FUNCTION__)); |
1368 | for (auto Pair : zip(Ty->subtypes(), ChildTypeIDs)) { |
1369 | assert(std::get<0>(Pair) == getTypeByID(std::get<1>(Pair)) &&(static_cast <bool> (std::get<0>(Pair) == getTypeByID (std::get<1>(Pair)) && "Incorrect contained type ID" ) ? void (0) : __assert_fail ("std::get<0>(Pair) == getTypeByID(std::get<1>(Pair)) && \"Incorrect contained type ID\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1370, __extension__ __PRETTY_FUNCTION__)) |
1370 | "Incorrect contained type ID")(static_cast <bool> (std::get<0>(Pair) == getTypeByID (std::get<1>(Pair)) && "Incorrect contained type ID" ) ? void (0) : __assert_fail ("std::get<0>(Pair) == getTypeByID(std::get<1>(Pair)) && \"Incorrect contained type ID\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1370, __extension__ __PRETTY_FUNCTION__)); |
1371 | } |
1372 | } |
1373 | #endif |
1374 | |
1375 | unsigned TypeID = TypeList.size(); |
1376 | TypeList.push_back(Ty); |
1377 | if (!ChildTypeIDs.empty()) |
1378 | append_range(ContainedTypeIDs[TypeID], ChildTypeIDs); |
1379 | VirtualTypeIDs.insert({CacheKey, TypeID}); |
1380 | return TypeID; |
1381 | } |
1382 | |
1383 | static bool isConstExprSupported(uint8_t Opcode) { |
1384 | // These are not real constant expressions, always consider them supported. |
1385 | if (Opcode >= BitcodeConstant::FirstSpecialOpcode) |
1386 | return true; |
1387 | |
1388 | // If -expand-constant-exprs is set, we want to consider all expressions |
1389 | // as unsupported. |
1390 | if (ExpandConstantExprs) |
1391 | return false; |
1392 | |
1393 | if (Instruction::isBinaryOp(Opcode)) |
1394 | return ConstantExpr::isSupportedBinOp(Opcode); |
1395 | |
1396 | return Opcode != Instruction::FNeg; |
1397 | } |
1398 | |
1399 | Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID, |
1400 | BasicBlock *InsertBB) { |
1401 | // Quickly handle the case where there is no BitcodeConstant to resolve. |
1402 | if (StartValID < ValueList.size() && ValueList[StartValID] && |
1403 | !isa<BitcodeConstant>(ValueList[StartValID])) |
1404 | return ValueList[StartValID]; |
1405 | |
1406 | SmallDenseMap<unsigned, Value *> MaterializedValues; |
1407 | SmallVector<unsigned> Worklist; |
1408 | Worklist.push_back(StartValID); |
1409 | while (!Worklist.empty()) { |
1410 | unsigned ValID = Worklist.back(); |
1411 | if (MaterializedValues.count(ValID)) { |
1412 | // Duplicate expression that was already handled. |
1413 | Worklist.pop_back(); |
1414 | continue; |
1415 | } |
1416 | |
1417 | if (ValID >= ValueList.size() || !ValueList[ValID]) |
1418 | return error("Invalid value ID"); |
1419 | |
1420 | Value *V = ValueList[ValID]; |
1421 | auto *BC = dyn_cast<BitcodeConstant>(V); |
1422 | if (!BC) { |
1423 | MaterializedValues.insert({ValID, V}); |
1424 | Worklist.pop_back(); |
1425 | continue; |
1426 | } |
1427 | |
1428 | // Iterate in reverse, so values will get popped from the worklist in |
1429 | // expected order. |
1430 | SmallVector<Value *> Ops; |
1431 | for (unsigned OpID : reverse(BC->getOperandIDs())) { |
1432 | auto It = MaterializedValues.find(OpID); |
1433 | if (It != MaterializedValues.end()) |
1434 | Ops.push_back(It->second); |
1435 | else |
1436 | Worklist.push_back(OpID); |
1437 | } |
1438 | |
1439 | // Some expressions have not been resolved yet, handle them first and then |
1440 | // revisit this one. |
1441 | if (Ops.size() != BC->getOperandIDs().size()) |
1442 | continue; |
1443 | std::reverse(Ops.begin(), Ops.end()); |
1444 | |
1445 | SmallVector<Constant *> ConstOps; |
1446 | for (Value *Op : Ops) |
1447 | if (auto *C = dyn_cast<Constant>(Op)) |
1448 | ConstOps.push_back(C); |
1449 | |
1450 | // Materialize as constant expression if possible. |
1451 | if (isConstExprSupported(BC->Opcode) && ConstOps.size() == Ops.size()) { |
1452 | Constant *C; |
1453 | if (Instruction::isCast(BC->Opcode)) { |
1454 | C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType()); |
1455 | if (!C) |
1456 | C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType()); |
1457 | } else if (Instruction::isBinaryOp(BC->Opcode)) { |
1458 | C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags); |
1459 | } else { |
1460 | switch (BC->Opcode) { |
1461 | case BitcodeConstant::NoCFIOpcode: { |
1462 | auto *GV = dyn_cast<GlobalValue>(ConstOps[0]); |
1463 | if (!GV) |
1464 | return error("no_cfi operand must be GlobalValue"); |
1465 | C = NoCFIValue::get(GV); |
1466 | break; |
1467 | } |
1468 | case BitcodeConstant::DSOLocalEquivalentOpcode: { |
1469 | auto *GV = dyn_cast<GlobalValue>(ConstOps[0]); |
1470 | if (!GV) |
1471 | return error("dso_local operand must be GlobalValue"); |
1472 | C = DSOLocalEquivalent::get(GV); |
1473 | break; |
1474 | } |
1475 | case BitcodeConstant::BlockAddressOpcode: { |
1476 | Function *Fn = dyn_cast<Function>(ConstOps[0]); |
1477 | if (!Fn) |
1478 | return error("blockaddress operand must be a function"); |
1479 | |
1480 | // If the function is already parsed we can insert the block address |
1481 | // right away. |
1482 | BasicBlock *BB; |
1483 | unsigned BBID = BC->Extra; |
1484 | if (!BBID) |
1485 | // Invalid reference to entry block. |
1486 | return error("Invalid ID"); |
1487 | if (!Fn->empty()) { |
1488 | Function::iterator BBI = Fn->begin(), BBE = Fn->end(); |
1489 | for (size_t I = 0, E = BBID; I != E; ++I) { |
1490 | if (BBI == BBE) |
1491 | return error("Invalid ID"); |
1492 | ++BBI; |
1493 | } |
1494 | BB = &*BBI; |
1495 | } else { |
1496 | // Otherwise insert a placeholder and remember it so it can be |
1497 | // inserted when the function is parsed. |
1498 | auto &FwdBBs = BasicBlockFwdRefs[Fn]; |
1499 | if (FwdBBs.empty()) |
1500 | BasicBlockFwdRefQueue.push_back(Fn); |
1501 | if (FwdBBs.size() < BBID + 1) |
1502 | FwdBBs.resize(BBID + 1); |
1503 | if (!FwdBBs[BBID]) |
1504 | FwdBBs[BBID] = BasicBlock::Create(Context); |
1505 | BB = FwdBBs[BBID]; |
1506 | } |
1507 | C = BlockAddress::get(Fn, BB); |
1508 | break; |
1509 | } |
1510 | case BitcodeConstant::ConstantStructOpcode: |
1511 | C = ConstantStruct::get(cast<StructType>(BC->getType()), ConstOps); |
1512 | break; |
1513 | case BitcodeConstant::ConstantArrayOpcode: |
1514 | C = ConstantArray::get(cast<ArrayType>(BC->getType()), ConstOps); |
1515 | break; |
1516 | case BitcodeConstant::ConstantVectorOpcode: |
1517 | C = ConstantVector::get(ConstOps); |
1518 | break; |
1519 | case Instruction::ICmp: |
1520 | case Instruction::FCmp: |
1521 | C = ConstantExpr::getCompare(BC->Flags, ConstOps[0], ConstOps[1]); |
1522 | break; |
1523 | case Instruction::GetElementPtr: |
1524 | C = ConstantExpr::getGetElementPtr( |
1525 | BC->SrcElemTy, ConstOps[0], makeArrayRef(ConstOps).drop_front(), |
1526 | BC->Flags, BC->getInRangeIndex()); |
1527 | break; |
1528 | case Instruction::Select: |
1529 | C = ConstantExpr::getSelect(ConstOps[0], ConstOps[1], ConstOps[2]); |
1530 | break; |
1531 | case Instruction::ExtractElement: |
1532 | C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]); |
1533 | break; |
1534 | case Instruction::InsertElement: |
1535 | C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1], |
1536 | ConstOps[2]); |
1537 | break; |
1538 | case Instruction::ShuffleVector: { |
1539 | SmallVector<int, 16> Mask; |
1540 | ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask); |
1541 | C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask); |
1542 | break; |
1543 | } |
1544 | default: |
1545 | llvm_unreachable("Unhandled bitcode constant")::llvm::llvm_unreachable_internal("Unhandled bitcode constant" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1545); |
1546 | } |
1547 | } |
1548 | |
1549 | // Cache resolved constant. |
1550 | ValueList.replaceValueWithoutRAUW(ValID, C); |
1551 | MaterializedValues.insert({ValID, C}); |
1552 | Worklist.pop_back(); |
1553 | continue; |
1554 | } |
1555 | |
1556 | if (!InsertBB) |
1557 | return error(Twine("Value referenced by initializer is an unsupported " |
1558 | "constant expression of type ") + |
1559 | BC->getOpcodeName()); |
1560 | |
1561 | // Materialize as instructions if necessary. |
1562 | Instruction *I; |
1563 | if (Instruction::isCast(BC->Opcode)) { |
1564 | I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0], |
1565 | BC->getType(), "constexpr", InsertBB); |
1566 | } else if (Instruction::isUnaryOp(BC->Opcode)) { |
1567 | I = UnaryOperator::Create((Instruction::UnaryOps)BC->Opcode, Ops[0], |
1568 | "constexpr", InsertBB); |
1569 | } else if (Instruction::isBinaryOp(BC->Opcode)) { |
1570 | I = BinaryOperator::Create((Instruction::BinaryOps)BC->Opcode, Ops[0], |
1571 | Ops[1], "constexpr", InsertBB); |
1572 | if (isa<OverflowingBinaryOperator>(I)) { |
1573 | if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap) |
1574 | I->setHasNoSignedWrap(); |
1575 | if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap) |
1576 | I->setHasNoUnsignedWrap(); |
1577 | } |
1578 | if (isa<PossiblyExactOperator>(I) && |
1579 | (BC->Flags & PossiblyExactOperator::IsExact)) |
1580 | I->setIsExact(); |
1581 | } else { |
1582 | switch (BC->Opcode) { |
1583 | case BitcodeConstant::ConstantVectorOpcode: { |
1584 | Type *IdxTy = Type::getInt32Ty(BC->getContext()); |
1585 | Value *V = PoisonValue::get(BC->getType()); |
1586 | for (auto Pair : enumerate(Ops)) { |
1587 | Value *Idx = ConstantInt::get(IdxTy, Pair.index()); |
1588 | V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins", |
1589 | InsertBB); |
1590 | } |
1591 | I = cast<Instruction>(V); |
1592 | break; |
1593 | } |
1594 | case BitcodeConstant::ConstantStructOpcode: |
1595 | case BitcodeConstant::ConstantArrayOpcode: { |
1596 | Value *V = PoisonValue::get(BC->getType()); |
1597 | for (auto Pair : enumerate(Ops)) |
1598 | V = InsertValueInst::Create(V, Pair.value(), Pair.index(), |
1599 | "constexpr.ins", InsertBB); |
1600 | I = cast<Instruction>(V); |
1601 | break; |
1602 | } |
1603 | case Instruction::ICmp: |
1604 | case Instruction::FCmp: |
1605 | I = CmpInst::Create((Instruction::OtherOps)BC->Opcode, |
1606 | (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1], |
1607 | "constexpr", InsertBB); |
1608 | break; |
1609 | case Instruction::GetElementPtr: |
1610 | I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0], |
1611 | makeArrayRef(Ops).drop_front(), |
1612 | "constexpr", InsertBB); |
1613 | if (BC->Flags) |
1614 | cast<GetElementPtrInst>(I)->setIsInBounds(); |
1615 | break; |
1616 | case Instruction::Select: |
1617 | I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB); |
1618 | break; |
1619 | case Instruction::ExtractElement: |
1620 | I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB); |
1621 | break; |
1622 | case Instruction::InsertElement: |
1623 | I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", |
1624 | InsertBB); |
1625 | break; |
1626 | case Instruction::ShuffleVector: |
1627 | I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr", |
1628 | InsertBB); |
1629 | break; |
1630 | default: |
1631 | llvm_unreachable("Unhandled bitcode constant")::llvm::llvm_unreachable_internal("Unhandled bitcode constant" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1631); |
1632 | } |
1633 | } |
1634 | |
1635 | MaterializedValues.insert({ValID, I}); |
1636 | Worklist.pop_back(); |
1637 | } |
1638 | |
1639 | return MaterializedValues[StartValID]; |
1640 | } |
1641 | |
1642 | Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) { |
1643 | Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr); |
1644 | if (!MaybeV) |
1645 | return MaybeV.takeError(); |
1646 | |
1647 | // Result must be Constant if InsertBB is nullptr. |
1648 | return cast<Constant>(MaybeV.get()); |
1649 | } |
1650 | |
1651 | StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, |
1652 | StringRef Name) { |
1653 | auto *Ret = StructType::create(Context, Name); |
1654 | IdentifiedStructTypes.push_back(Ret); |
1655 | return Ret; |
1656 | } |
1657 | |
1658 | StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { |
1659 | auto *Ret = StructType::create(Context); |
1660 | IdentifiedStructTypes.push_back(Ret); |
1661 | return Ret; |
1662 | } |
1663 | |
1664 | //===----------------------------------------------------------------------===// |
1665 | // Functions for parsing blocks from the bitcode file |
1666 | //===----------------------------------------------------------------------===// |
1667 | |
1668 | static uint64_t getRawAttributeMask(Attribute::AttrKind Val) { |
1669 | switch (Val) { |
1670 | case Attribute::EndAttrKinds: |
1671 | case Attribute::EmptyKey: |
1672 | case Attribute::TombstoneKey: |
1673 | llvm_unreachable("Synthetic enumerators which should never get here")::llvm::llvm_unreachable_internal("Synthetic enumerators which should never get here" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1673); |
1674 | |
1675 | case Attribute::None: return 0; |
1676 | case Attribute::ZExt: return 1 << 0; |
1677 | case Attribute::SExt: return 1 << 1; |
1678 | case Attribute::NoReturn: return 1 << 2; |
1679 | case Attribute::InReg: return 1 << 3; |
1680 | case Attribute::StructRet: return 1 << 4; |
1681 | case Attribute::NoUnwind: return 1 << 5; |
1682 | case Attribute::NoAlias: return 1 << 6; |
1683 | case Attribute::ByVal: return 1 << 7; |
1684 | case Attribute::Nest: return 1 << 8; |
1685 | case Attribute::ReadNone: return 1 << 9; |
1686 | case Attribute::ReadOnly: return 1 << 10; |
1687 | case Attribute::NoInline: return 1 << 11; |
1688 | case Attribute::AlwaysInline: return 1 << 12; |
1689 | case Attribute::OptimizeForSize: return 1 << 13; |
1690 | case Attribute::StackProtect: return 1 << 14; |
1691 | case Attribute::StackProtectReq: return 1 << 15; |
1692 | case Attribute::Alignment: return 31 << 16; |
1693 | case Attribute::NoCapture: return 1 << 21; |
1694 | case Attribute::NoRedZone: return 1 << 22; |
1695 | case Attribute::NoImplicitFloat: return 1 << 23; |
1696 | case Attribute::Naked: return 1 << 24; |
1697 | case Attribute::InlineHint: return 1 << 25; |
1698 | case Attribute::StackAlignment: return 7 << 26; |
1699 | case Attribute::ReturnsTwice: return 1 << 29; |
1700 | case Attribute::UWTable: return 1 << 30; |
1701 | case Attribute::NonLazyBind: return 1U << 31; |
1702 | case Attribute::SanitizeAddress: return 1ULL << 32; |
1703 | case Attribute::MinSize: return 1ULL << 33; |
1704 | case Attribute::NoDuplicate: return 1ULL << 34; |
1705 | case Attribute::StackProtectStrong: return 1ULL << 35; |
1706 | case Attribute::SanitizeThread: return 1ULL << 36; |
1707 | case Attribute::SanitizeMemory: return 1ULL << 37; |
1708 | case Attribute::NoBuiltin: return 1ULL << 38; |
1709 | case Attribute::Returned: return 1ULL << 39; |
1710 | case Attribute::Cold: return 1ULL << 40; |
1711 | case Attribute::Builtin: return 1ULL << 41; |
1712 | case Attribute::OptimizeNone: return 1ULL << 42; |
1713 | case Attribute::InAlloca: return 1ULL << 43; |
1714 | case Attribute::NonNull: return 1ULL << 44; |
1715 | case Attribute::JumpTable: return 1ULL << 45; |
1716 | case Attribute::Convergent: return 1ULL << 46; |
1717 | case Attribute::SafeStack: return 1ULL << 47; |
1718 | case Attribute::NoRecurse: return 1ULL << 48; |
1719 | case Attribute::InaccessibleMemOnly: return 1ULL << 49; |
1720 | case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50; |
1721 | case Attribute::SwiftSelf: return 1ULL << 51; |
1722 | case Attribute::SwiftError: return 1ULL << 52; |
1723 | case Attribute::WriteOnly: return 1ULL << 53; |
1724 | case Attribute::Speculatable: return 1ULL << 54; |
1725 | case Attribute::StrictFP: return 1ULL << 55; |
1726 | case Attribute::SanitizeHWAddress: return 1ULL << 56; |
1727 | case Attribute::NoCfCheck: return 1ULL << 57; |
1728 | case Attribute::OptForFuzzing: return 1ULL << 58; |
1729 | case Attribute::ShadowCallStack: return 1ULL << 59; |
1730 | case Attribute::SpeculativeLoadHardening: |
1731 | return 1ULL << 60; |
1732 | case Attribute::ImmArg: |
1733 | return 1ULL << 61; |
1734 | case Attribute::WillReturn: |
1735 | return 1ULL << 62; |
1736 | case Attribute::NoFree: |
1737 | return 1ULL << 63; |
1738 | default: |
1739 | // Other attributes are not supported in the raw format, |
1740 | // as we ran out of space. |
1741 | return 0; |
1742 | } |
1743 | llvm_unreachable("Unsupported attribute type")::llvm::llvm_unreachable_internal("Unsupported attribute type" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1743); |
1744 | } |
1745 | |
1746 | static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { |
1747 | if (!Val) return; |
1748 | |
1749 | for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; |
1750 | I = Attribute::AttrKind(I + 1)) { |
1751 | if (uint64_t A = (Val & getRawAttributeMask(I))) { |
1752 | if (I == Attribute::Alignment) |
1753 | B.addAlignmentAttr(1ULL << ((A >> 16) - 1)); |
1754 | else if (I == Attribute::StackAlignment) |
1755 | B.addStackAlignmentAttr(1ULL << ((A >> 26)-1)); |
1756 | else if (Attribute::isTypeAttrKind(I)) |
1757 | B.addTypeAttr(I, nullptr); // Type will be auto-upgraded. |
1758 | else |
1759 | B.addAttribute(I); |
1760 | } |
1761 | } |
1762 | } |
1763 | |
1764 | /// This fills an AttrBuilder object with the LLVM attributes that have |
1765 | /// been decoded from the given integer. This function must stay in sync with |
1766 | /// 'encodeLLVMAttributesForBitcode'. |
1767 | static void decodeLLVMAttributesForBitcode(AttrBuilder &B, |
1768 | uint64_t EncodedAttrs) { |
1769 | // The alignment is stored as a 16-bit raw value from bits 31--16. We shift |
1770 | // the bits above 31 down by 11 bits. |
1771 | unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; |
1772 | assert((!Alignment || isPowerOf2_32(Alignment)) &&(static_cast <bool> ((!Alignment || isPowerOf2_32(Alignment )) && "Alignment must be a power of two.") ? void (0) : __assert_fail ("(!Alignment || isPowerOf2_32(Alignment)) && \"Alignment must be a power of two.\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1773, __extension__ __PRETTY_FUNCTION__)) |
1773 | "Alignment must be a power of two.")(static_cast <bool> ((!Alignment || isPowerOf2_32(Alignment )) && "Alignment must be a power of two.") ? void (0) : __assert_fail ("(!Alignment || isPowerOf2_32(Alignment)) && \"Alignment must be a power of two.\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 1773, __extension__ __PRETTY_FUNCTION__)); |
1774 | |
1775 | if (Alignment) |
1776 | B.addAlignmentAttr(Alignment); |
1777 | addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | |
1778 | (EncodedAttrs & 0xffff)); |
1779 | } |
1780 | |
1781 | Error BitcodeReader::parseAttributeBlock() { |
1782 | if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) |
1783 | return Err; |
1784 | |
1785 | if (!MAttributes.empty()) |
1786 | return error("Invalid multiple blocks"); |
1787 | |
1788 | SmallVector<uint64_t, 64> Record; |
1789 | |
1790 | SmallVector<AttributeList, 8> Attrs; |
1791 | |
1792 | // Read all the records. |
1793 | while (true) { |
1794 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
1795 | if (!MaybeEntry) |
1796 | return MaybeEntry.takeError(); |
1797 | BitstreamEntry Entry = MaybeEntry.get(); |
1798 | |
1799 | switch (Entry.Kind) { |
1800 | case BitstreamEntry::SubBlock: // Handled for us already. |
1801 | case BitstreamEntry::Error: |
1802 | return error("Malformed block"); |
1803 | case BitstreamEntry::EndBlock: |
1804 | return Error::success(); |
1805 | case BitstreamEntry::Record: |
1806 | // The interesting case. |
1807 | break; |
1808 | } |
1809 | |
1810 | // Read a record. |
1811 | Record.clear(); |
1812 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
1813 | if (!MaybeRecord) |
1814 | return MaybeRecord.takeError(); |
1815 | switch (MaybeRecord.get()) { |
1816 | default: // Default behavior: ignore. |
1817 | break; |
1818 | case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...] |
1819 | // Deprecated, but still needed to read old bitcode files. |
1820 | if (Record.size() & 1) |
1821 | return error("Invalid parameter attribute record"); |
1822 | |
1823 | for (unsigned i = 0, e = Record.size(); i != e; i += 2) { |
1824 | AttrBuilder B(Context); |
1825 | decodeLLVMAttributesForBitcode(B, Record[i+1]); |
1826 | Attrs.push_back(AttributeList::get(Context, Record[i], B)); |
1827 | } |
1828 | |
1829 | MAttributes.push_back(AttributeList::get(Context, Attrs)); |
1830 | Attrs.clear(); |
1831 | break; |
1832 | case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...] |
1833 | for (unsigned i = 0, e = Record.size(); i != e; ++i) |
1834 | Attrs.push_back(MAttributeGroups[Record[i]]); |
1835 | |
1836 | MAttributes.push_back(AttributeList::get(Context, Attrs)); |
1837 | Attrs.clear(); |
1838 | break; |
1839 | } |
1840 | } |
1841 | } |
1842 | |
1843 | // Returns Attribute::None on unrecognized codes. |
1844 | static Attribute::AttrKind getAttrFromCode(uint64_t Code) { |
1845 | switch (Code) { |
1846 | default: |
1847 | return Attribute::None; |
1848 | case bitc::ATTR_KIND_ALIGNMENT: |
1849 | return Attribute::Alignment; |
1850 | case bitc::ATTR_KIND_ALWAYS_INLINE: |
1851 | return Attribute::AlwaysInline; |
1852 | case bitc::ATTR_KIND_ARGMEMONLY: |
1853 | return Attribute::ArgMemOnly; |
1854 | case bitc::ATTR_KIND_BUILTIN: |
1855 | return Attribute::Builtin; |
1856 | case bitc::ATTR_KIND_BY_VAL: |
1857 | return Attribute::ByVal; |
1858 | case bitc::ATTR_KIND_IN_ALLOCA: |
1859 | return Attribute::InAlloca; |
1860 | case bitc::ATTR_KIND_COLD: |
1861 | return Attribute::Cold; |
1862 | case bitc::ATTR_KIND_CONVERGENT: |
1863 | return Attribute::Convergent; |
1864 | case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION: |
1865 | return Attribute::DisableSanitizerInstrumentation; |
1866 | case bitc::ATTR_KIND_ELEMENTTYPE: |
1867 | return Attribute::ElementType; |
1868 | case bitc::ATTR_KIND_FNRETTHUNK_EXTERN: |
1869 | return Attribute::FnRetThunkExtern; |
1870 | case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: |
1871 | return Attribute::InaccessibleMemOnly; |
1872 | case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: |
1873 | return Attribute::InaccessibleMemOrArgMemOnly; |
1874 | case bitc::ATTR_KIND_INLINE_HINT: |
1875 | return Attribute::InlineHint; |
1876 | case bitc::ATTR_KIND_IN_REG: |
1877 | return Attribute::InReg; |
1878 | case bitc::ATTR_KIND_JUMP_TABLE: |
1879 | return Attribute::JumpTable; |
1880 | case bitc::ATTR_KIND_MIN_SIZE: |
1881 | return Attribute::MinSize; |
1882 | case bitc::ATTR_KIND_NAKED: |
1883 | return Attribute::Naked; |
1884 | case bitc::ATTR_KIND_NEST: |
1885 | return Attribute::Nest; |
1886 | case bitc::ATTR_KIND_NO_ALIAS: |
1887 | return Attribute::NoAlias; |
1888 | case bitc::ATTR_KIND_NO_BUILTIN: |
1889 | return Attribute::NoBuiltin; |
1890 | case bitc::ATTR_KIND_NO_CALLBACK: |
1891 | return Attribute::NoCallback; |
1892 | case bitc::ATTR_KIND_NO_CAPTURE: |
1893 | return Attribute::NoCapture; |
1894 | case bitc::ATTR_KIND_NO_DUPLICATE: |
1895 | return Attribute::NoDuplicate; |
1896 | case bitc::ATTR_KIND_NOFREE: |
1897 | return Attribute::NoFree; |
1898 | case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: |
1899 | return Attribute::NoImplicitFloat; |
1900 | case bitc::ATTR_KIND_NO_INLINE: |
1901 | return Attribute::NoInline; |
1902 | case bitc::ATTR_KIND_NO_RECURSE: |
1903 | return Attribute::NoRecurse; |
1904 | case bitc::ATTR_KIND_NO_MERGE: |
1905 | return Attribute::NoMerge; |
1906 | case bitc::ATTR_KIND_NON_LAZY_BIND: |
1907 | return Attribute::NonLazyBind; |
1908 | case bitc::ATTR_KIND_NON_NULL: |
1909 | return Attribute::NonNull; |
1910 | case bitc::ATTR_KIND_DEREFERENCEABLE: |
1911 | return Attribute::Dereferenceable; |
1912 | case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: |
1913 | return Attribute::DereferenceableOrNull; |
1914 | case bitc::ATTR_KIND_ALLOC_ALIGN: |
1915 | return Attribute::AllocAlign; |
1916 | case bitc::ATTR_KIND_ALLOC_KIND: |
1917 | return Attribute::AllocKind; |
1918 | case bitc::ATTR_KIND_ALLOC_SIZE: |
1919 | return Attribute::AllocSize; |
1920 | case bitc::ATTR_KIND_ALLOCATED_POINTER: |
1921 | return Attribute::AllocatedPointer; |
1922 | case bitc::ATTR_KIND_NO_RED_ZONE: |
1923 | return Attribute::NoRedZone; |
1924 | case bitc::ATTR_KIND_NO_RETURN: |
1925 | return Attribute::NoReturn; |
1926 | case bitc::ATTR_KIND_NOSYNC: |
1927 | return Attribute::NoSync; |
1928 | case bitc::ATTR_KIND_NOCF_CHECK: |
1929 | return Attribute::NoCfCheck; |
1930 | case bitc::ATTR_KIND_NO_PROFILE: |
1931 | return Attribute::NoProfile; |
1932 | case bitc::ATTR_KIND_SKIP_PROFILE: |
1933 | return Attribute::SkipProfile; |
1934 | case bitc::ATTR_KIND_NO_UNWIND: |
1935 | return Attribute::NoUnwind; |
1936 | case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS: |
1937 | return Attribute::NoSanitizeBounds; |
1938 | case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE: |
1939 | return Attribute::NoSanitizeCoverage; |
1940 | case bitc::ATTR_KIND_NULL_POINTER_IS_VALID: |
1941 | return Attribute::NullPointerIsValid; |
1942 | case bitc::ATTR_KIND_OPT_FOR_FUZZING: |
1943 | return Attribute::OptForFuzzing; |
1944 | case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: |
1945 | return Attribute::OptimizeForSize; |
1946 | case bitc::ATTR_KIND_OPTIMIZE_NONE: |
1947 | return Attribute::OptimizeNone; |
1948 | case bitc::ATTR_KIND_READ_NONE: |
1949 | return Attribute::ReadNone; |
1950 | case bitc::ATTR_KIND_READ_ONLY: |
1951 | return Attribute::ReadOnly; |
1952 | case bitc::ATTR_KIND_RETURNED: |
1953 | return Attribute::Returned; |
1954 | case bitc::ATTR_KIND_RETURNS_TWICE: |
1955 | return Attribute::ReturnsTwice; |
1956 | case bitc::ATTR_KIND_S_EXT: |
1957 | return Attribute::SExt; |
1958 | case bitc::ATTR_KIND_SPECULATABLE: |
1959 | return Attribute::Speculatable; |
1960 | case bitc::ATTR_KIND_STACK_ALIGNMENT: |
1961 | return Attribute::StackAlignment; |
1962 | case bitc::ATTR_KIND_STACK_PROTECT: |
1963 | return Attribute::StackProtect; |
1964 | case bitc::ATTR_KIND_STACK_PROTECT_REQ: |
1965 | return Attribute::StackProtectReq; |
1966 | case bitc::ATTR_KIND_STACK_PROTECT_STRONG: |
1967 | return Attribute::StackProtectStrong; |
1968 | case bitc::ATTR_KIND_SAFESTACK: |
1969 | return Attribute::SafeStack; |
1970 | case bitc::ATTR_KIND_SHADOWCALLSTACK: |
1971 | return Attribute::ShadowCallStack; |
1972 | case bitc::ATTR_KIND_STRICT_FP: |
1973 | return Attribute::StrictFP; |
1974 | case bitc::ATTR_KIND_STRUCT_RET: |
1975 | return Attribute::StructRet; |
1976 | case bitc::ATTR_KIND_SANITIZE_ADDRESS: |
1977 | return Attribute::SanitizeAddress; |
1978 | case bitc::ATTR_KIND_SANITIZE_HWADDRESS: |
1979 | return Attribute::SanitizeHWAddress; |
1980 | case bitc::ATTR_KIND_SANITIZE_THREAD: |
1981 | return Attribute::SanitizeThread; |
1982 | case bitc::ATTR_KIND_SANITIZE_MEMORY: |
1983 | return Attribute::SanitizeMemory; |
1984 | case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING: |
1985 | return Attribute::SpeculativeLoadHardening; |
1986 | case bitc::ATTR_KIND_SWIFT_ERROR: |
1987 | return Attribute::SwiftError; |
1988 | case bitc::ATTR_KIND_SWIFT_SELF: |
1989 | return Attribute::SwiftSelf; |
1990 | case bitc::ATTR_KIND_SWIFT_ASYNC: |
1991 | return Attribute::SwiftAsync; |
1992 | case bitc::ATTR_KIND_UW_TABLE: |
1993 | return Attribute::UWTable; |
1994 | case bitc::ATTR_KIND_VSCALE_RANGE: |
1995 | return Attribute::VScaleRange; |
1996 | case bitc::ATTR_KIND_WILLRETURN: |
1997 | return Attribute::WillReturn; |
1998 | case bitc::ATTR_KIND_WRITEONLY: |
1999 | return Attribute::WriteOnly; |
2000 | case bitc::ATTR_KIND_Z_EXT: |
2001 | return Attribute::ZExt; |
2002 | case bitc::ATTR_KIND_IMMARG: |
2003 | return Attribute::ImmArg; |
2004 | case bitc::ATTR_KIND_SANITIZE_MEMTAG: |
2005 | return Attribute::SanitizeMemTag; |
2006 | case bitc::ATTR_KIND_PREALLOCATED: |
2007 | return Attribute::Preallocated; |
2008 | case bitc::ATTR_KIND_NOUNDEF: |
2009 | return Attribute::NoUndef; |
2010 | case bitc::ATTR_KIND_BYREF: |
2011 | return Attribute::ByRef; |
2012 | case bitc::ATTR_KIND_MUSTPROGRESS: |
2013 | return Attribute::MustProgress; |
2014 | case bitc::ATTR_KIND_HOT: |
2015 | return Attribute::Hot; |
2016 | case bitc::ATTR_KIND_PRESPLIT_COROUTINE: |
2017 | return Attribute::PresplitCoroutine; |
2018 | } |
2019 | } |
2020 | |
2021 | Error BitcodeReader::parseAlignmentValue(uint64_t Exponent, |
2022 | MaybeAlign &Alignment) { |
2023 | // Note: Alignment in bitcode files is incremented by 1, so that zero |
2024 | // can be used for default alignment. |
2025 | if (Exponent > Value::MaxAlignmentExponent + 1) |
2026 | return error("Invalid alignment value"); |
2027 | Alignment = decodeMaybeAlign(Exponent); |
2028 | return Error::success(); |
2029 | } |
2030 | |
2031 | Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) { |
2032 | *Kind = getAttrFromCode(Code); |
2033 | if (*Kind == Attribute::None) |
2034 | return error("Unknown attribute kind (" + Twine(Code) + ")"); |
2035 | return Error::success(); |
2036 | } |
2037 | |
2038 | Error BitcodeReader::parseAttributeGroupBlock() { |
2039 | if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) |
2040 | return Err; |
2041 | |
2042 | if (!MAttributeGroups.empty()) |
2043 | return error("Invalid multiple blocks"); |
2044 | |
2045 | SmallVector<uint64_t, 64> Record; |
2046 | |
2047 | // Read all the records. |
2048 | while (true) { |
2049 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
2050 | if (!MaybeEntry) |
2051 | return MaybeEntry.takeError(); |
2052 | BitstreamEntry Entry = MaybeEntry.get(); |
2053 | |
2054 | switch (Entry.Kind) { |
2055 | case BitstreamEntry::SubBlock: // Handled for us already. |
2056 | case BitstreamEntry::Error: |
2057 | return error("Malformed block"); |
2058 | case BitstreamEntry::EndBlock: |
2059 | return Error::success(); |
2060 | case BitstreamEntry::Record: |
2061 | // The interesting case. |
2062 | break; |
2063 | } |
2064 | |
2065 | // Read a record. |
2066 | Record.clear(); |
2067 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
2068 | if (!MaybeRecord) |
2069 | return MaybeRecord.takeError(); |
2070 | switch (MaybeRecord.get()) { |
2071 | default: // Default behavior: ignore. |
2072 | break; |
2073 | case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] |
2074 | if (Record.size() < 3) |
2075 | return error("Invalid grp record"); |
2076 | |
2077 | uint64_t GrpID = Record[0]; |
2078 | uint64_t Idx = Record[1]; // Index of the object this attribute refers to. |
2079 | |
2080 | AttrBuilder B(Context); |
2081 | for (unsigned i = 2, e = Record.size(); i != e; ++i) { |
2082 | if (Record[i] == 0) { // Enum attribute |
2083 | Attribute::AttrKind Kind; |
2084 | if (Error Err = parseAttrKind(Record[++i], &Kind)) |
2085 | return Err; |
2086 | |
2087 | // Upgrade old-style byval attribute to one with a type, even if it's |
2088 | // nullptr. We will have to insert the real type when we associate |
2089 | // this AttributeList with a function. |
2090 | if (Kind == Attribute::ByVal) |
2091 | B.addByValAttr(nullptr); |
2092 | else if (Kind == Attribute::StructRet) |
2093 | B.addStructRetAttr(nullptr); |
2094 | else if (Kind == Attribute::InAlloca) |
2095 | B.addInAllocaAttr(nullptr); |
2096 | else if (Kind == Attribute::UWTable) |
2097 | B.addUWTableAttr(UWTableKind::Default); |
2098 | else if (Attribute::isEnumAttrKind(Kind)) |
2099 | B.addAttribute(Kind); |
2100 | else |
2101 | return error("Not an enum attribute"); |
2102 | } else if (Record[i] == 1) { // Integer attribute |
2103 | Attribute::AttrKind Kind; |
2104 | if (Error Err = parseAttrKind(Record[++i], &Kind)) |
2105 | return Err; |
2106 | if (!Attribute::isIntAttrKind(Kind)) |
2107 | return error("Not an int attribute"); |
2108 | if (Kind == Attribute::Alignment) |
2109 | B.addAlignmentAttr(Record[++i]); |
2110 | else if (Kind == Attribute::StackAlignment) |
2111 | B.addStackAlignmentAttr(Record[++i]); |
2112 | else if (Kind == Attribute::Dereferenceable) |
2113 | B.addDereferenceableAttr(Record[++i]); |
2114 | else if (Kind == Attribute::DereferenceableOrNull) |
2115 | B.addDereferenceableOrNullAttr(Record[++i]); |
2116 | else if (Kind == Attribute::AllocSize) |
2117 | B.addAllocSizeAttrFromRawRepr(Record[++i]); |
2118 | else if (Kind == Attribute::VScaleRange) |
2119 | B.addVScaleRangeAttrFromRawRepr(Record[++i]); |
2120 | else if (Kind == Attribute::UWTable) |
2121 | B.addUWTableAttr(UWTableKind(Record[++i])); |
2122 | else if (Kind == Attribute::AllocKind) |
2123 | B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i])); |
2124 | } else if (Record[i] == 3 || Record[i] == 4) { // String attribute |
2125 | bool HasValue = (Record[i++] == 4); |
2126 | SmallString<64> KindStr; |
2127 | SmallString<64> ValStr; |
2128 | |
2129 | while (Record[i] != 0 && i != e) |
2130 | KindStr += Record[i++]; |
2131 | assert(Record[i] == 0 && "Kind string not null terminated")(static_cast <bool> (Record[i] == 0 && "Kind string not null terminated" ) ? void (0) : __assert_fail ("Record[i] == 0 && \"Kind string not null terminated\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 2131, __extension__ __PRETTY_FUNCTION__)); |
2132 | |
2133 | if (HasValue) { |
2134 | // Has a value associated with it. |
2135 | ++i; // Skip the '0' that terminates the "kind" string. |
2136 | while (Record[i] != 0 && i != e) |
2137 | ValStr += Record[i++]; |
2138 | assert(Record[i] == 0 && "Value string not null terminated")(static_cast <bool> (Record[i] == 0 && "Value string not null terminated" ) ? void (0) : __assert_fail ("Record[i] == 0 && \"Value string not null terminated\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 2138, __extension__ __PRETTY_FUNCTION__)); |
2139 | } |
2140 | |
2141 | B.addAttribute(KindStr.str(), ValStr.str()); |
2142 | } else if (Record[i] == 5 || Record[i] == 6) { |
2143 | bool HasType = Record[i] == 6; |
2144 | Attribute::AttrKind Kind; |
2145 | if (Error Err = parseAttrKind(Record[++i], &Kind)) |
2146 | return Err; |
2147 | if (!Attribute::isTypeAttrKind(Kind)) |
2148 | return error("Not a type attribute"); |
2149 | |
2150 | B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr); |
2151 | } else { |
2152 | return error("Invalid attribute group entry"); |
2153 | } |
2154 | } |
2155 | |
2156 | UpgradeAttributes(B); |
2157 | MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B); |
2158 | break; |
2159 | } |
2160 | } |
2161 | } |
2162 | } |
2163 | |
2164 | Error BitcodeReader::parseTypeTable() { |
2165 | if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) |
2166 | return Err; |
2167 | |
2168 | return parseTypeTableBody(); |
2169 | } |
2170 | |
2171 | Error BitcodeReader::parseTypeTableBody() { |
2172 | if (!TypeList.empty()) |
2173 | return error("Invalid multiple blocks"); |
2174 | |
2175 | SmallVector<uint64_t, 64> Record; |
2176 | unsigned NumRecords = 0; |
2177 | |
2178 | SmallString<64> TypeName; |
2179 | |
2180 | // Read all the records for this type table. |
2181 | while (true) { |
2182 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
2183 | if (!MaybeEntry) |
2184 | return MaybeEntry.takeError(); |
2185 | BitstreamEntry Entry = MaybeEntry.get(); |
2186 | |
2187 | switch (Entry.Kind) { |
2188 | case BitstreamEntry::SubBlock: // Handled for us already. |
2189 | case BitstreamEntry::Error: |
2190 | return error("Malformed block"); |
2191 | case BitstreamEntry::EndBlock: |
2192 | if (NumRecords != TypeList.size()) |
2193 | return error("Malformed block"); |
2194 | return Error::success(); |
2195 | case BitstreamEntry::Record: |
2196 | // The interesting case. |
2197 | break; |
2198 | } |
2199 | |
2200 | // Read a record. |
2201 | Record.clear(); |
2202 | Type *ResultTy = nullptr; |
2203 | SmallVector<unsigned> ContainedIDs; |
2204 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
2205 | if (!MaybeRecord) |
2206 | return MaybeRecord.takeError(); |
2207 | switch (MaybeRecord.get()) { |
2208 | default: |
2209 | return error("Invalid value"); |
2210 | case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] |
2211 | // TYPE_CODE_NUMENTRY contains a count of the number of types in the |
2212 | // type list. This allows us to reserve space. |
2213 | if (Record.empty()) |
2214 | return error("Invalid numentry record"); |
2215 | TypeList.resize(Record[0]); |
2216 | continue; |
2217 | case bitc::TYPE_CODE_VOID: // VOID |
2218 | ResultTy = Type::getVoidTy(Context); |
2219 | break; |
2220 | case bitc::TYPE_CODE_HALF: // HALF |
2221 | ResultTy = Type::getHalfTy(Context); |
2222 | break; |
2223 | case bitc::TYPE_CODE_BFLOAT: // BFLOAT |
2224 | ResultTy = Type::getBFloatTy(Context); |
2225 | break; |
2226 | case bitc::TYPE_CODE_FLOAT: // FLOAT |
2227 | ResultTy = Type::getFloatTy(Context); |
2228 | break; |
2229 | case bitc::TYPE_CODE_DOUBLE: // DOUBLE |
2230 | ResultTy = Type::getDoubleTy(Context); |
2231 | break; |
2232 | case bitc::TYPE_CODE_X86_FP80: // X86_FP80 |
2233 | ResultTy = Type::getX86_FP80Ty(Context); |
2234 | break; |
2235 | case bitc::TYPE_CODE_FP128: // FP128 |
2236 | ResultTy = Type::getFP128Ty(Context); |
2237 | break; |
2238 | case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 |
2239 | ResultTy = Type::getPPC_FP128Ty(Context); |
2240 | break; |
2241 | case bitc::TYPE_CODE_LABEL: // LABEL |
2242 | ResultTy = Type::getLabelTy(Context); |
2243 | break; |
2244 | case bitc::TYPE_CODE_METADATA: // METADATA |
2245 | ResultTy = Type::getMetadataTy(Context); |
2246 | break; |
2247 | case bitc::TYPE_CODE_X86_MMX: // X86_MMX |
2248 | ResultTy = Type::getX86_MMXTy(Context); |
2249 | break; |
2250 | case bitc::TYPE_CODE_X86_AMX: // X86_AMX |
2251 | ResultTy = Type::getX86_AMXTy(Context); |
2252 | break; |
2253 | case bitc::TYPE_CODE_TOKEN: // TOKEN |
2254 | ResultTy = Type::getTokenTy(Context); |
2255 | break; |
2256 | case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] |
2257 | if (Record.empty()) |
2258 | return error("Invalid integer record"); |
2259 | |
2260 | uint64_t NumBits = Record[0]; |
2261 | if (NumBits < IntegerType::MIN_INT_BITS || |
2262 | NumBits > IntegerType::MAX_INT_BITS) |
2263 | return error("Bitwidth for integer type out of range"); |
2264 | ResultTy = IntegerType::get(Context, NumBits); |
2265 | break; |
2266 | } |
2267 | case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or |
2268 | // [pointee type, address space] |
2269 | if (Record.empty()) |
2270 | return error("Invalid pointer record"); |
2271 | unsigned AddressSpace = 0; |
2272 | if (Record.size() == 2) |
2273 | AddressSpace = Record[1]; |
2274 | ResultTy = getTypeByID(Record[0]); |
2275 | if (!ResultTy || |
2276 | !PointerType::isValidElementType(ResultTy)) |
2277 | return error("Invalid type"); |
2278 | if (LLVM_UNLIKELY(!Context.hasSetOpaquePointersValue())__builtin_expect((bool)(!Context.hasSetOpaquePointersValue()) , false)) |
2279 | Context.setOpaquePointers(false); |
2280 | ContainedIDs.push_back(Record[0]); |
2281 | ResultTy = PointerType::get(ResultTy, AddressSpace); |
2282 | break; |
2283 | } |
2284 | case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace] |
2285 | if (Record.size() != 1) |
2286 | return error("Invalid opaque pointer record"); |
2287 | if (LLVM_UNLIKELY(!Context.hasSetOpaquePointersValue())__builtin_expect((bool)(!Context.hasSetOpaquePointersValue()) , false)) { |
2288 | Context.setOpaquePointers(true); |
2289 | } else if (Context.supportsTypedPointers()) |
2290 | return error( |
2291 | "Opaque pointers are only supported in -opaque-pointers mode"); |
2292 | unsigned AddressSpace = Record[0]; |
2293 | ResultTy = PointerType::get(Context, AddressSpace); |
2294 | break; |
2295 | } |
2296 | case bitc::TYPE_CODE_FUNCTION_OLD: { |
2297 | // Deprecated, but still needed to read old bitcode files. |
2298 | // FUNCTION: [vararg, attrid, retty, paramty x N] |
2299 | if (Record.size() < 3) |
2300 | return error("Invalid function record"); |
2301 | SmallVector<Type*, 8> ArgTys; |
2302 | for (unsigned i = 3, e = Record.size(); i != e; ++i) { |
2303 | if (Type *T = getTypeByID(Record[i])) |
2304 | ArgTys.push_back(T); |
2305 | else |
2306 | break; |
2307 | } |
2308 | |
2309 | ResultTy = getTypeByID(Record[2]); |
2310 | if (!ResultTy || ArgTys.size() < Record.size()-3) |
2311 | return error("Invalid type"); |
2312 | |
2313 | ContainedIDs.append(Record.begin() + 2, Record.end()); |
2314 | ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); |
2315 | break; |
2316 | } |
2317 | case bitc::TYPE_CODE_FUNCTION: { |
2318 | // FUNCTION: [vararg, retty, paramty x N] |
2319 | if (Record.size() < 2) |
2320 | return error("Invalid function record"); |
2321 | SmallVector<Type*, 8> ArgTys; |
2322 | for (unsigned i = 2, e = Record.size(); i != e; ++i) { |
2323 | if (Type *T = getTypeByID(Record[i])) { |
2324 | if (!FunctionType::isValidArgumentType(T)) |
2325 | return error("Invalid function argument type"); |
2326 | ArgTys.push_back(T); |
2327 | } |
2328 | else |
2329 | break; |
2330 | } |
2331 | |
2332 | ResultTy = getTypeByID(Record[1]); |
2333 | if (!ResultTy || ArgTys.size() < Record.size()-2) |
2334 | return error("Invalid type"); |
2335 | |
2336 | ContainedIDs.append(Record.begin() + 1, Record.end()); |
2337 | ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); |
2338 | break; |
2339 | } |
2340 | case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] |
2341 | if (Record.empty()) |
2342 | return error("Invalid anon struct record"); |
2343 | SmallVector<Type*, 8> EltTys; |
2344 | for (unsigned i = 1, e = Record.size(); i != e; ++i) { |
2345 | if (Type *T = getTypeByID(Record[i])) |
2346 | EltTys.push_back(T); |
2347 | else |
2348 | break; |
2349 | } |
2350 | if (EltTys.size() != Record.size()-1) |
2351 | return error("Invalid type"); |
2352 | ContainedIDs.append(Record.begin() + 1, Record.end()); |
2353 | ResultTy = StructType::get(Context, EltTys, Record[0]); |
2354 | break; |
2355 | } |
2356 | case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] |
2357 | if (convertToString(Record, 0, TypeName)) |
2358 | return error("Invalid struct name record"); |
2359 | continue; |
2360 | |
2361 | case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] |
2362 | if (Record.empty()) |
2363 | return error("Invalid named struct record"); |
2364 | |
2365 | if (NumRecords >= TypeList.size()) |
2366 | return error("Invalid TYPE table"); |
2367 | |
2368 | // Check to see if this was forward referenced, if so fill in the temp. |
2369 | StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); |
2370 | if (Res) { |
2371 | Res->setName(TypeName); |
2372 | TypeList[NumRecords] = nullptr; |
2373 | } else // Otherwise, create a new struct. |
2374 | Res = createIdentifiedStructType(Context, TypeName); |
2375 | TypeName.clear(); |
2376 | |
2377 | SmallVector<Type*, 8> EltTys; |
2378 | for (unsigned i = 1, e = Record.size(); i != e; ++i) { |
2379 | if (Type *T = getTypeByID(Record[i])) |
2380 | EltTys.push_back(T); |
2381 | else |
2382 | break; |
2383 | } |
2384 | if (EltTys.size() != Record.size()-1) |
2385 | return error("Invalid named struct record"); |
2386 | Res->setBody(EltTys, Record[0]); |
2387 | ContainedIDs.append(Record.begin() + 1, Record.end()); |
2388 | ResultTy = Res; |
2389 | break; |
2390 | } |
2391 | case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] |
2392 | if (Record.size() != 1) |
2393 | return error("Invalid opaque type record"); |
2394 | |
2395 | if (NumRecords >= TypeList.size()) |
2396 | return error("Invalid TYPE table"); |
2397 | |
2398 | // Check to see if this was forward referenced, if so fill in the temp. |
2399 | StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); |
2400 | if (Res) { |
2401 | Res->setName(TypeName); |
2402 | TypeList[NumRecords] = nullptr; |
2403 | } else // Otherwise, create a new struct with no body. |
2404 | Res = createIdentifiedStructType(Context, TypeName); |
2405 | TypeName.clear(); |
2406 | ResultTy = Res; |
2407 | break; |
2408 | } |
2409 | case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] |
2410 | if (Record.size() < 2) |
2411 | return error("Invalid array type record"); |
2412 | ResultTy = getTypeByID(Record[1]); |
2413 | if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) |
2414 | return error("Invalid type"); |
2415 | ContainedIDs.push_back(Record[1]); |
2416 | ResultTy = ArrayType::get(ResultTy, Record[0]); |
2417 | break; |
2418 | case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or |
2419 | // [numelts, eltty, scalable] |
2420 | if (Record.size() < 2) |
2421 | return error("Invalid vector type record"); |
2422 | if (Record[0] == 0) |
2423 | return error("Invalid vector length"); |
2424 | ResultTy = getTypeByID(Record[1]); |
2425 | if (!ResultTy || !VectorType::isValidElementType(ResultTy)) |
2426 | return error("Invalid type"); |
2427 | bool Scalable = Record.size() > 2 ? Record[2] : false; |
2428 | ContainedIDs.push_back(Record[1]); |
2429 | ResultTy = VectorType::get(ResultTy, Record[0], Scalable); |
2430 | break; |
2431 | } |
2432 | |
2433 | if (NumRecords >= TypeList.size()) |
2434 | return error("Invalid TYPE table"); |
2435 | if (TypeList[NumRecords]) |
2436 | return error( |
2437 | "Invalid TYPE table: Only named structs can be forward referenced"); |
2438 | assert(ResultTy && "Didn't read a type?")(static_cast <bool> (ResultTy && "Didn't read a type?" ) ? void (0) : __assert_fail ("ResultTy && \"Didn't read a type?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 2438, __extension__ __PRETTY_FUNCTION__)); |
2439 | TypeList[NumRecords] = ResultTy; |
2440 | if (!ContainedIDs.empty()) |
2441 | ContainedTypeIDs[NumRecords] = std::move(ContainedIDs); |
2442 | ++NumRecords; |
2443 | } |
2444 | } |
2445 | |
2446 | Error BitcodeReader::parseOperandBundleTags() { |
2447 | if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) |
2448 | return Err; |
2449 | |
2450 | if (!BundleTags.empty()) |
2451 | return error("Invalid multiple blocks"); |
2452 | |
2453 | SmallVector<uint64_t, 64> Record; |
2454 | |
2455 | while (true) { |
2456 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
2457 | if (!MaybeEntry) |
2458 | return MaybeEntry.takeError(); |
2459 | BitstreamEntry Entry = MaybeEntry.get(); |
2460 | |
2461 | switch (Entry.Kind) { |
2462 | case BitstreamEntry::SubBlock: // Handled for us already. |
2463 | case BitstreamEntry::Error: |
2464 | return error("Malformed block"); |
2465 | case BitstreamEntry::EndBlock: |
2466 | return Error::success(); |
2467 | case BitstreamEntry::Record: |
2468 | // The interesting case. |
2469 | break; |
2470 | } |
2471 | |
2472 | // Tags are implicitly mapped to integers by their order. |
2473 | |
2474 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
2475 | if (!MaybeRecord) |
2476 | return MaybeRecord.takeError(); |
2477 | if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG) |
2478 | return error("Invalid operand bundle record"); |
2479 | |
2480 | // OPERAND_BUNDLE_TAG: [strchr x N] |
2481 | BundleTags.emplace_back(); |
2482 | if (convertToString(Record, 0, BundleTags.back())) |
2483 | return error("Invalid operand bundle record"); |
2484 | Record.clear(); |
2485 | } |
2486 | } |
2487 | |
2488 | Error BitcodeReader::parseSyncScopeNames() { |
2489 | if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID)) |
2490 | return Err; |
2491 | |
2492 | if (!SSIDs.empty()) |
2493 | return error("Invalid multiple synchronization scope names blocks"); |
2494 | |
2495 | SmallVector<uint64_t, 64> Record; |
2496 | while (true) { |
2497 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
2498 | if (!MaybeEntry) |
2499 | return MaybeEntry.takeError(); |
2500 | BitstreamEntry Entry = MaybeEntry.get(); |
2501 | |
2502 | switch (Entry.Kind) { |
2503 | case BitstreamEntry::SubBlock: // Handled for us already. |
2504 | case BitstreamEntry::Error: |
2505 | return error("Malformed block"); |
2506 | case BitstreamEntry::EndBlock: |
2507 | if (SSIDs.empty()) |
2508 | return error("Invalid empty synchronization scope names block"); |
2509 | return Error::success(); |
2510 | case BitstreamEntry::Record: |
2511 | // The interesting case. |
2512 | break; |
2513 | } |
2514 | |
2515 | // Synchronization scope names are implicitly mapped to synchronization |
2516 | // scope IDs by their order. |
2517 | |
2518 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
2519 | if (!MaybeRecord) |
2520 | return MaybeRecord.takeError(); |
2521 | if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME) |
2522 | return error("Invalid sync scope record"); |
2523 | |
2524 | SmallString<16> SSN; |
2525 | if (convertToString(Record, 0, SSN)) |
2526 | return error("Invalid sync scope record"); |
2527 | |
2528 | SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN)); |
2529 | Record.clear(); |
2530 | } |
2531 | } |
2532 | |
2533 | /// Associate a value with its name from the given index in the provided record. |
2534 | Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, |
2535 | unsigned NameIndex, Triple &TT) { |
2536 | SmallString<128> ValueName; |
2537 | if (convertToString(Record, NameIndex, ValueName)) |
2538 | return error("Invalid record"); |
2539 | unsigned ValueID = Record[0]; |
2540 | if (ValueID >= ValueList.size() || !ValueList[ValueID]) |
2541 | return error("Invalid record"); |
2542 | Value *V = ValueList[ValueID]; |
2543 | |
2544 | StringRef NameStr(ValueName.data(), ValueName.size()); |
2545 | if (NameStr.find_first_of(0) != StringRef::npos) |
2546 | return error("Invalid value name"); |
2547 | V->setName(NameStr); |
2548 | auto *GO = dyn_cast<GlobalObject>(V); |
2549 | if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT()) |
2550 | GO->setComdat(TheModule->getOrInsertComdat(V->getName())); |
2551 | return V; |
2552 | } |
2553 | |
2554 | /// Helper to note and return the current location, and jump to the given |
2555 | /// offset. |
2556 | static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset, |
2557 | BitstreamCursor &Stream) { |
2558 | // Save the current parsing location so we can jump back at the end |
2559 | // of the VST read. |
2560 | uint64_t CurrentBit = Stream.GetCurrentBitNo(); |
2561 | if (Error JumpFailed = Stream.JumpToBit(Offset * 32)) |
2562 | return std::move(JumpFailed); |
2563 | Expected<BitstreamEntry> MaybeEntry = Stream.advance(); |
2564 | if (!MaybeEntry) |
2565 | return MaybeEntry.takeError(); |
2566 | if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock || |
2567 | MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID) |
2568 | return error("Expected value symbol table subblock"); |
2569 | return CurrentBit; |
2570 | } |
2571 | |
2572 | void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, |
2573 | Function *F, |
2574 | ArrayRef<uint64_t> Record) { |
2575 | // Note that we subtract 1 here because the offset is relative to one word |
2576 | // before the start of the identification or module block, which was |
2577 | // historically always the start of the regular bitcode header. |
2578 | uint64_t FuncWordOffset = Record[1] - 1; |
2579 | uint64_t FuncBitOffset = FuncWordOffset * 32; |
2580 | DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; |
2581 | // Set the LastFunctionBlockBit to point to the last function block. |
2582 | // Later when parsing is resumed after function materialization, |
2583 | // we can simply skip that last function block. |
2584 | if (FuncBitOffset > LastFunctionBlockBit) |
2585 | LastFunctionBlockBit = FuncBitOffset; |
2586 | } |
2587 | |
2588 | /// Read a new-style GlobalValue symbol table. |
2589 | Error BitcodeReader::parseGlobalValueSymbolTable() { |
2590 | unsigned FuncBitcodeOffsetDelta = |
2591 | Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; |
2592 | |
2593 | if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) |
2594 | return Err; |
2595 | |
2596 | SmallVector<uint64_t, 64> Record; |
2597 | while (true) { |
2598 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
2599 | if (!MaybeEntry) |
2600 | return MaybeEntry.takeError(); |
2601 | BitstreamEntry Entry = MaybeEntry.get(); |
2602 | |
2603 | switch (Entry.Kind) { |
2604 | case BitstreamEntry::SubBlock: |
2605 | case BitstreamEntry::Error: |
2606 | return error("Malformed block"); |
2607 | case BitstreamEntry::EndBlock: |
2608 | return Error::success(); |
2609 | case BitstreamEntry::Record: |
2610 | break; |
2611 | } |
2612 | |
2613 | Record.clear(); |
2614 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
2615 | if (!MaybeRecord) |
2616 | return MaybeRecord.takeError(); |
2617 | switch (MaybeRecord.get()) { |
2618 | case bitc::VST_CODE_FNENTRY: { // [valueid, offset] |
2619 | unsigned ValueID = Record[0]; |
2620 | if (ValueID >= ValueList.size() || !ValueList[ValueID]) |
2621 | return error("Invalid value reference in symbol table"); |
2622 | setDeferredFunctionInfo(FuncBitcodeOffsetDelta, |
2623 | cast<Function>(ValueList[ValueID]), Record); |
2624 | break; |
2625 | } |
2626 | } |
2627 | } |
2628 | } |
2629 | |
2630 | /// Parse the value symbol table at either the current parsing location or |
2631 | /// at the given bit offset if provided. |
2632 | Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) { |
2633 | uint64_t CurrentBit; |
2634 | // Pass in the Offset to distinguish between calling for the module-level |
2635 | // VST (where we want to jump to the VST offset) and the function-level |
2636 | // VST (where we don't). |
2637 | if (Offset > 0) { |
2638 | Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); |
2639 | if (!MaybeCurrentBit) |
2640 | return MaybeCurrentBit.takeError(); |
2641 | CurrentBit = MaybeCurrentBit.get(); |
2642 | // If this module uses a string table, read this as a module-level VST. |
2643 | if (UseStrtab) { |
2644 | if (Error Err = parseGlobalValueSymbolTable()) |
2645 | return Err; |
2646 | if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) |
2647 | return JumpFailed; |
2648 | return Error::success(); |
2649 | } |
2650 | // Otherwise, the VST will be in a similar format to a function-level VST, |
2651 | // and will contain symbol names. |
2652 | } |
2653 | |
2654 | // Compute the delta between the bitcode indices in the VST (the word offset |
2655 | // to the word-aligned ENTER_SUBBLOCK for the function block, and that |
2656 | // expected by the lazy reader. The reader's EnterSubBlock expects to have |
2657 | // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID |
2658 | // (size BlockIDWidth). Note that we access the stream's AbbrevID width here |
2659 | // just before entering the VST subblock because: 1) the EnterSubBlock |
2660 | // changes the AbbrevID width; 2) the VST block is nested within the same |
2661 | // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same |
2662 | // AbbrevID width before calling EnterSubBlock; and 3) when we want to |
2663 | // jump to the FUNCTION_BLOCK using this offset later, we don't want |
2664 | // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. |
2665 | unsigned FuncBitcodeOffsetDelta = |
2666 | Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; |
2667 | |
2668 | if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) |
2669 | return Err; |
2670 | |
2671 | SmallVector<uint64_t, 64> Record; |
2672 | |
2673 | Triple TT(TheModule->getTargetTriple()); |
2674 | |
2675 | // Read all the records for this value table. |
2676 | SmallString<128> ValueName; |
2677 | |
2678 | while (true) { |
2679 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
2680 | if (!MaybeEntry) |
2681 | return MaybeEntry.takeError(); |
2682 | BitstreamEntry Entry = MaybeEntry.get(); |
2683 | |
2684 | switch (Entry.Kind) { |
2685 | case BitstreamEntry::SubBlock: // Handled for us already. |
2686 | case BitstreamEntry::Error: |
2687 | return error("Malformed block"); |
2688 | case BitstreamEntry::EndBlock: |
2689 | if (Offset > 0) |
2690 | if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) |
2691 | return JumpFailed; |
2692 | return Error::success(); |
2693 | case BitstreamEntry::Record: |
2694 | // The interesting case. |
2695 | break; |
2696 | } |
2697 | |
2698 | // Read a record. |
2699 | Record.clear(); |
2700 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
2701 | if (!MaybeRecord) |
2702 | return MaybeRecord.takeError(); |
2703 | switch (MaybeRecord.get()) { |
2704 | default: // Default behavior: unknown type. |
2705 | break; |
2706 | case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] |
2707 | Expected<Value *> ValOrErr = recordValue(Record, 1, TT); |
2708 | if (Error Err = ValOrErr.takeError()) |
2709 | return Err; |
2710 | ValOrErr.get(); |
2711 | break; |
2712 | } |
2713 | case bitc::VST_CODE_FNENTRY: { |
2714 | // VST_CODE_FNENTRY: [valueid, offset, namechar x N] |
2715 | Expected<Value *> ValOrErr = recordValue(Record, 2, TT); |
2716 | if (Error Err = ValOrErr.takeError()) |
2717 | return Err; |
2718 | Value *V = ValOrErr.get(); |
2719 | |
2720 | // Ignore function offsets emitted for aliases of functions in older |
2721 | // versions of LLVM. |
2722 | if (auto *F = dyn_cast<Function>(V)) |
2723 | setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record); |
2724 | break; |
2725 | } |
2726 | case bitc::VST_CODE_BBENTRY: { |
2727 | if (convertToString(Record, 1, ValueName)) |
2728 | return error("Invalid bbentry record"); |
2729 | BasicBlock *BB = getBasicBlock(Record[0]); |
2730 | if (!BB) |
2731 | return error("Invalid bbentry record"); |
2732 | |
2733 | BB->setName(StringRef(ValueName.data(), ValueName.size())); |
2734 | ValueName.clear(); |
2735 | break; |
2736 | } |
2737 | } |
2738 | } |
2739 | } |
2740 | |
2741 | /// Decode a signed value stored with the sign bit in the LSB for dense VBR |
2742 | /// encoding. |
2743 | uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { |
2744 | if ((V & 1) == 0) |
2745 | return V >> 1; |
2746 | if (V != 1) |
2747 | return -(V >> 1); |
2748 | // There is no such thing as -0 with integers. "-0" really means MININT. |
2749 | return 1ULL << 63; |
2750 | } |
2751 | |
2752 | /// Resolve all of the initializers for global values and aliases that we can. |
2753 | Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() { |
2754 | std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist; |
2755 | std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist; |
2756 | std::vector<FunctionOperandInfo> FunctionOperandWorklist; |
2757 | |
2758 | GlobalInitWorklist.swap(GlobalInits); |
2759 | IndirectSymbolInitWorklist.swap(IndirectSymbolInits); |
2760 | FunctionOperandWorklist.swap(FunctionOperands); |
2761 | |
2762 | while (!GlobalInitWorklist.empty()) { |
2763 | unsigned ValID = GlobalInitWorklist.back().second; |
2764 | if (ValID >= ValueList.size()) { |
2765 | // Not ready to resolve this yet, it requires something later in the file. |
2766 | GlobalInits.push_back(GlobalInitWorklist.back()); |
2767 | } else { |
2768 | Expected<Constant *> MaybeC = getValueForInitializer(ValID); |
2769 | if (!MaybeC) |
2770 | return MaybeC.takeError(); |
2771 | GlobalInitWorklist.back().first->setInitializer(MaybeC.get()); |
2772 | } |
2773 | GlobalInitWorklist.pop_back(); |
2774 | } |
2775 | |
2776 | while (!IndirectSymbolInitWorklist.empty()) { |
2777 | unsigned ValID = IndirectSymbolInitWorklist.back().second; |
2778 | if (ValID >= ValueList.size()) { |
2779 | IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back()); |
2780 | } else { |
2781 | Expected<Constant *> MaybeC = getValueForInitializer(ValID); |
2782 | if (!MaybeC) |
2783 | return MaybeC.takeError(); |
2784 | Constant *C = MaybeC.get(); |
2785 | GlobalValue *GV = IndirectSymbolInitWorklist.back().first; |
2786 | if (auto *GA = dyn_cast<GlobalAlias>(GV)) { |
2787 | if (C->getType() != GV->getType()) |
2788 | return error("Alias and aliasee types don't match"); |
2789 | GA->setAliasee(C); |
2790 | } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) { |
2791 | Type *ResolverFTy = |
2792 | GlobalIFunc::getResolverFunctionType(GI->getValueType()); |
2793 | // Transparently fix up the type for compatibility with older bitcode |
2794 | GI->setResolver( |
2795 | ConstantExpr::getBitCast(C, ResolverFTy->getPointerTo())); |
2796 | } else { |
2797 | return error("Expected an alias or an ifunc"); |
2798 | } |
2799 | } |
2800 | IndirectSymbolInitWorklist.pop_back(); |
2801 | } |
2802 | |
2803 | while (!FunctionOperandWorklist.empty()) { |
2804 | FunctionOperandInfo &Info = FunctionOperandWorklist.back(); |
2805 | if (Info.PersonalityFn) { |
2806 | unsigned ValID = Info.PersonalityFn - 1; |
2807 | if (ValID < ValueList.size()) { |
2808 | Expected<Constant *> MaybeC = getValueForInitializer(ValID); |
2809 | if (!MaybeC) |
2810 | return MaybeC.takeError(); |
2811 | Info.F->setPersonalityFn(MaybeC.get()); |
2812 | Info.PersonalityFn = 0; |
2813 | } |
2814 | } |
2815 | if (Info.Prefix) { |
2816 | unsigned ValID = Info.Prefix - 1; |
2817 | if (ValID < ValueList.size()) { |
2818 | Expected<Constant *> MaybeC = getValueForInitializer(ValID); |
2819 | if (!MaybeC) |
2820 | return MaybeC.takeError(); |
2821 | Info.F->setPrefixData(MaybeC.get()); |
2822 | Info.Prefix = 0; |
2823 | } |
2824 | } |
2825 | if (Info.Prologue) { |
2826 | unsigned ValID = Info.Prologue - 1; |
2827 | if (ValID < ValueList.size()) { |
2828 | Expected<Constant *> MaybeC = getValueForInitializer(ValID); |
2829 | if (!MaybeC) |
2830 | return MaybeC.takeError(); |
2831 | Info.F->setPrologueData(MaybeC.get()); |
2832 | Info.Prologue = 0; |
2833 | } |
2834 | } |
2835 | if (Info.PersonalityFn || Info.Prefix || Info.Prologue) |
2836 | FunctionOperands.push_back(Info); |
2837 | FunctionOperandWorklist.pop_back(); |
2838 | } |
2839 | |
2840 | return Error::success(); |
2841 | } |
2842 | |
2843 | APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { |
2844 | SmallVector<uint64_t, 8> Words(Vals.size()); |
2845 | transform(Vals, Words.begin(), |
2846 | BitcodeReader::decodeSignRotatedValue); |
2847 | |
2848 | return APInt(TypeBits, Words); |
2849 | } |
2850 | |
2851 | Error BitcodeReader::parseConstants() { |
2852 | if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) |
2853 | return Err; |
2854 | |
2855 | SmallVector<uint64_t, 64> Record; |
2856 | |
2857 | // Read all the records for this value table. |
2858 | Type *CurTy = Type::getInt32Ty(Context); |
2859 | unsigned Int32TyID = getVirtualTypeID(CurTy); |
2860 | unsigned CurTyID = Int32TyID; |
2861 | Type *CurElemTy = nullptr; |
2862 | unsigned NextCstNo = ValueList.size(); |
2863 | |
2864 | while (true) { |
2865 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
2866 | if (!MaybeEntry) |
2867 | return MaybeEntry.takeError(); |
2868 | BitstreamEntry Entry = MaybeEntry.get(); |
2869 | |
2870 | switch (Entry.Kind) { |
2871 | case BitstreamEntry::SubBlock: // Handled for us already. |
2872 | case BitstreamEntry::Error: |
2873 | return error("Malformed block"); |
2874 | case BitstreamEntry::EndBlock: |
2875 | if (NextCstNo != ValueList.size()) |
2876 | return error("Invalid constant reference"); |
2877 | return Error::success(); |
2878 | case BitstreamEntry::Record: |
2879 | // The interesting case. |
2880 | break; |
2881 | } |
2882 | |
2883 | // Read a record. |
2884 | Record.clear(); |
2885 | Type *VoidType = Type::getVoidTy(Context); |
2886 | Value *V = nullptr; |
2887 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); |
2888 | if (!MaybeBitCode) |
2889 | return MaybeBitCode.takeError(); |
2890 | switch (unsigned BitCode = MaybeBitCode.get()) { |
2891 | default: // Default behavior: unknown constant |
2892 | case bitc::CST_CODE_UNDEF: // UNDEF |
2893 | V = UndefValue::get(CurTy); |
2894 | break; |
2895 | case bitc::CST_CODE_POISON: // POISON |
2896 | V = PoisonValue::get(CurTy); |
2897 | break; |
2898 | case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] |
2899 | if (Record.empty()) |
2900 | return error("Invalid settype record"); |
2901 | if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) |
2902 | return error("Invalid settype record"); |
2903 | if (TypeList[Record[0]] == VoidType) |
2904 | return error("Invalid constant type"); |
2905 | CurTyID = Record[0]; |
2906 | CurTy = TypeList[CurTyID]; |
2907 | CurElemTy = getPtrElementTypeByID(CurTyID); |
2908 | continue; // Skip the ValueList manipulation. |
2909 | case bitc::CST_CODE_NULL: // NULL |
2910 | if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy()) |
2911 | return error("Invalid type for a constant null value"); |
2912 | V = Constant::getNullValue(CurTy); |
2913 | break; |
2914 | case bitc::CST_CODE_INTEGER: // INTEGER: [intval] |
2915 | if (!CurTy->isIntegerTy() || Record.empty()) |
2916 | return error("Invalid integer const record"); |
2917 | V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); |
2918 | break; |
2919 | case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] |
2920 | if (!CurTy->isIntegerTy() || Record.empty()) |
2921 | return error("Invalid wide integer const record"); |
2922 | |
2923 | APInt VInt = |
2924 | readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); |
2925 | V = ConstantInt::get(Context, VInt); |
2926 | |
2927 | break; |
2928 | } |
2929 | case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] |
2930 | if (Record.empty()) |
2931 | return error("Invalid float const record"); |
2932 | if (CurTy->isHalfTy()) |
2933 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(), |
2934 | APInt(16, (uint16_t)Record[0]))); |
2935 | else if (CurTy->isBFloatTy()) |
2936 | V = ConstantFP::get(Context, APFloat(APFloat::BFloat(), |
2937 | APInt(16, (uint32_t)Record[0]))); |
2938 | else if (CurTy->isFloatTy()) |
2939 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(), |
2940 | APInt(32, (uint32_t)Record[0]))); |
2941 | else if (CurTy->isDoubleTy()) |
2942 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(), |
2943 | APInt(64, Record[0]))); |
2944 | else if (CurTy->isX86_FP80Ty()) { |
2945 | // Bits are not stored the same way as a normal i80 APInt, compensate. |
2946 | uint64_t Rearrange[2]; |
2947 | Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); |
2948 | Rearrange[1] = Record[0] >> 48; |
2949 | V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(), |
2950 | APInt(80, Rearrange))); |
2951 | } else if (CurTy->isFP128Ty()) |
2952 | V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(), |
2953 | APInt(128, Record))); |
2954 | else if (CurTy->isPPC_FP128Ty()) |
2955 | V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(), |
2956 | APInt(128, Record))); |
2957 | else |
2958 | V = UndefValue::get(CurTy); |
2959 | break; |
2960 | } |
2961 | |
2962 | case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] |
2963 | if (Record.empty()) |
2964 | return error("Invalid aggregate record"); |
2965 | |
2966 | unsigned Size = Record.size(); |
2967 | SmallVector<unsigned, 16> Elts; |
2968 | for (unsigned i = 0; i != Size; ++i) |
2969 | Elts.push_back(Record[i]); |
2970 | |
2971 | if (isa<StructType>(CurTy)) { |
2972 | V = BitcodeConstant::create( |
2973 | Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts); |
2974 | } else if (isa<ArrayType>(CurTy)) { |
2975 | V = BitcodeConstant::create(Alloc, CurTy, |
2976 | BitcodeConstant::ConstantArrayOpcode, Elts); |
2977 | } else if (isa<VectorType>(CurTy)) { |
2978 | V = BitcodeConstant::create( |
2979 | Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts); |
2980 | } else { |
2981 | V = UndefValue::get(CurTy); |
2982 | } |
2983 | break; |
2984 | } |
2985 | case bitc::CST_CODE_STRING: // STRING: [values] |
2986 | case bitc::CST_CODE_CSTRING: { // CSTRING: [values] |
2987 | if (Record.empty()) |
2988 | return error("Invalid string record"); |
2989 | |
2990 | SmallString<16> Elts(Record.begin(), Record.end()); |
2991 | V = ConstantDataArray::getString(Context, Elts, |
2992 | BitCode == bitc::CST_CODE_CSTRING); |
2993 | break; |
2994 | } |
2995 | case bitc::CST_CODE_DATA: {// DATA: [n x value] |
2996 | if (Record.empty()) |
2997 | return error("Invalid data record"); |
2998 | |
2999 | Type *EltTy; |
3000 | if (auto *Array = dyn_cast<ArrayType>(CurTy)) |
3001 | EltTy = Array->getElementType(); |
3002 | else |
3003 | EltTy = cast<VectorType>(CurTy)->getElementType(); |
3004 | if (EltTy->isIntegerTy(8)) { |
3005 | SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); |
3006 | if (isa<VectorType>(CurTy)) |
3007 | V = ConstantDataVector::get(Context, Elts); |
3008 | else |
3009 | V = ConstantDataArray::get(Context, Elts); |
3010 | } else if (EltTy->isIntegerTy(16)) { |
3011 | SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); |
3012 | if (isa<VectorType>(CurTy)) |
3013 | V = ConstantDataVector::get(Context, Elts); |
3014 | else |
3015 | V = ConstantDataArray::get(Context, Elts); |
3016 | } else if (EltTy->isIntegerTy(32)) { |
3017 | SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); |
3018 | if (isa<VectorType>(CurTy)) |
3019 | V = ConstantDataVector::get(Context, Elts); |
3020 | else |
3021 | V = ConstantDataArray::get(Context, Elts); |
3022 | } else if (EltTy->isIntegerTy(64)) { |
3023 | SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); |
3024 | if (isa<VectorType>(CurTy)) |
3025 | V = ConstantDataVector::get(Context, Elts); |
3026 | else |
3027 | V = ConstantDataArray::get(Context, Elts); |
3028 | } else if (EltTy->isHalfTy()) { |
3029 | SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); |
3030 | if (isa<VectorType>(CurTy)) |
3031 | V = ConstantDataVector::getFP(EltTy, Elts); |
3032 | else |
3033 | V = ConstantDataArray::getFP(EltTy, Elts); |
3034 | } else if (EltTy->isBFloatTy()) { |
3035 | SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); |
3036 | if (isa<VectorType>(CurTy)) |
3037 | V = ConstantDataVector::getFP(EltTy, Elts); |
3038 | else |
3039 | V = ConstantDataArray::getFP(EltTy, Elts); |
3040 | } else if (EltTy->isFloatTy()) { |
3041 | SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); |
3042 | if (isa<VectorType>(CurTy)) |
3043 | V = ConstantDataVector::getFP(EltTy, Elts); |
3044 | else |
3045 | V = ConstantDataArray::getFP(EltTy, Elts); |
3046 | } else if (EltTy->isDoubleTy()) { |
3047 | SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); |
3048 | if (isa<VectorType>(CurTy)) |
3049 | V = ConstantDataVector::getFP(EltTy, Elts); |
3050 | else |
3051 | V = ConstantDataArray::getFP(EltTy, Elts); |
3052 | } else { |
3053 | return error("Invalid type for value"); |
3054 | } |
3055 | break; |
3056 | } |
3057 | case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval] |
3058 | if (Record.size() < 2) |
3059 | return error("Invalid unary op constexpr record"); |
3060 | int Opc = getDecodedUnaryOpcode(Record[0], CurTy); |
3061 | if (Opc < 0) { |
3062 | V = UndefValue::get(CurTy); // Unknown unop. |
3063 | } else { |
3064 | V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]); |
3065 | } |
3066 | break; |
3067 | } |
3068 | case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] |
3069 | if (Record.size() < 3) |
3070 | return error("Invalid binary op constexpr record"); |
3071 | int Opc = getDecodedBinaryOpcode(Record[0], CurTy); |
3072 | if (Opc < 0) { |
3073 | V = UndefValue::get(CurTy); // Unknown binop. |
3074 | } else { |
3075 | uint8_t Flags = 0; |
3076 | if (Record.size() >= 4) { |
3077 | if (Opc == Instruction::Add || |
3078 | Opc == Instruction::Sub || |
3079 | Opc == Instruction::Mul || |
3080 | Opc == Instruction::Shl) { |
3081 | if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) |
3082 | Flags |= OverflowingBinaryOperator::NoSignedWrap; |
3083 | if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) |
3084 | Flags |= OverflowingBinaryOperator::NoUnsignedWrap; |
3085 | } else if (Opc == Instruction::SDiv || |
3086 | Opc == Instruction::UDiv || |
3087 | Opc == Instruction::LShr || |
3088 | Opc == Instruction::AShr) { |
3089 | if (Record[3] & (1 << bitc::PEO_EXACT)) |
3090 | Flags |= SDivOperator::IsExact; |
3091 | } |
3092 | } |
3093 | V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags}, |
3094 | {(unsigned)Record[1], (unsigned)Record[2]}); |
3095 | } |
3096 | break; |
3097 | } |
3098 | case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] |
3099 | if (Record.size() < 3) |
3100 | return error("Invalid cast constexpr record"); |
3101 | int Opc = getDecodedCastOpcode(Record[0]); |
3102 | if (Opc < 0) { |
3103 | V = UndefValue::get(CurTy); // Unknown cast. |
3104 | } else { |
3105 | unsigned OpTyID = Record[1]; |
3106 | Type *OpTy = getTypeByID(OpTyID); |
3107 | if (!OpTy) |
3108 | return error("Invalid cast constexpr record"); |
3109 | V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]); |
3110 | } |
3111 | break; |
3112 | } |
3113 | case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] |
3114 | case bitc::CST_CODE_CE_GEP: // [ty, n x operands] |
3115 | case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x |
3116 | // operands] |
3117 | if (Record.size() < 2) |
3118 | return error("Constant GEP record must have at least two elements"); |
3119 | unsigned OpNum = 0; |
3120 | Type *PointeeType = nullptr; |
3121 | if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX || |
3122 | Record.size() % 2) |
3123 | PointeeType = getTypeByID(Record[OpNum++]); |
3124 | |
3125 | bool InBounds = false; |
3126 | Optional<unsigned> InRangeIndex; |
3127 | if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) { |
3128 | uint64_t Op = Record[OpNum++]; |
3129 | InBounds = Op & 1; |
3130 | InRangeIndex = Op >> 1; |
3131 | } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) |
3132 | InBounds = true; |
3133 | |
3134 | SmallVector<unsigned, 16> Elts; |
3135 | unsigned BaseTypeID = Record[OpNum]; |
3136 | while (OpNum != Record.size()) { |
3137 | unsigned ElTyID = Record[OpNum++]; |
3138 | Type *ElTy = getTypeByID(ElTyID); |
3139 | if (!ElTy) |
3140 | return error("Invalid getelementptr constexpr record"); |
3141 | Elts.push_back(Record[OpNum++]); |
3142 | } |
3143 | |
3144 | if (Elts.size() < 1) |
3145 | return error("Invalid gep with no operands"); |
3146 | |
3147 | Type *BaseType = getTypeByID(BaseTypeID); |
3148 | if (isa<VectorType>(BaseType)) { |
3149 | BaseTypeID = getContainedTypeID(BaseTypeID, 0); |
3150 | BaseType = getTypeByID(BaseTypeID); |
3151 | } |
3152 | |
3153 | PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType); |
3154 | if (!OrigPtrTy) |
3155 | return error("GEP base operand must be pointer or vector of pointer"); |
3156 | |
3157 | if (!PointeeType) { |
3158 | PointeeType = getPtrElementTypeByID(BaseTypeID); |
3159 | if (!PointeeType) |
3160 | return error("Missing element type for old-style constant GEP"); |
3161 | } else if (!OrigPtrTy->isOpaqueOrPointeeTypeMatches(PointeeType)) |
3162 | return error("Explicit gep operator type does not match pointee type " |
3163 | "of pointer operand"); |
3164 | |
3165 | V = BitcodeConstant::create(Alloc, CurTy, |
3166 | {Instruction::GetElementPtr, InBounds, |
3167 | InRangeIndex.value_or(-1), PointeeType}, |
3168 | Elts); |
3169 | break; |
3170 | } |
3171 | case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] |
3172 | if (Record.size() < 3) |
3173 | return error("Invalid select constexpr record"); |
3174 | |
3175 | V = BitcodeConstant::create( |
3176 | Alloc, CurTy, Instruction::Select, |
3177 | {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]}); |
3178 | break; |
3179 | } |
3180 | case bitc::CST_CODE_CE_EXTRACTELT |
3181 | : { // CE_EXTRACTELT: [opty, opval, opty, opval] |
3182 | if (Record.size() < 3) |
3183 | return error("Invalid extractelement constexpr record"); |
3184 | unsigned OpTyID = Record[0]; |
3185 | VectorType *OpTy = |
3186 | dyn_cast_or_null<VectorType>(getTypeByID(OpTyID)); |
3187 | if (!OpTy) |
3188 | return error("Invalid extractelement constexpr record"); |
3189 | unsigned IdxRecord; |
3190 | if (Record.size() == 4) { |
3191 | unsigned IdxTyID = Record[2]; |
3192 | Type *IdxTy = getTypeByID(IdxTyID); |
3193 | if (!IdxTy) |
3194 | return error("Invalid extractelement constexpr record"); |
3195 | IdxRecord = Record[3]; |
3196 | } else { |
3197 | // Deprecated, but still needed to read old bitcode files. |
3198 | IdxRecord = Record[2]; |
3199 | } |
3200 | V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement, |
3201 | {(unsigned)Record[1], IdxRecord}); |
3202 | break; |
3203 | } |
3204 | case bitc::CST_CODE_CE_INSERTELT |
3205 | : { // CE_INSERTELT: [opval, opval, opty, opval] |
3206 | VectorType *OpTy = dyn_cast<VectorType>(CurTy); |
3207 | if (Record.size() < 3 || !OpTy) |
3208 | return error("Invalid insertelement constexpr record"); |
3209 | unsigned IdxRecord; |
3210 | if (Record.size() == 4) { |
3211 | unsigned IdxTyID = Record[2]; |
3212 | Type *IdxTy = getTypeByID(IdxTyID); |
3213 | if (!IdxTy) |
3214 | return error("Invalid insertelement constexpr record"); |
3215 | IdxRecord = Record[3]; |
3216 | } else { |
3217 | // Deprecated, but still needed to read old bitcode files. |
3218 | IdxRecord = Record[2]; |
3219 | } |
3220 | V = BitcodeConstant::create( |
3221 | Alloc, CurTy, Instruction::InsertElement, |
3222 | {(unsigned)Record[0], (unsigned)Record[1], IdxRecord}); |
3223 | break; |
3224 | } |
3225 | case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] |
3226 | VectorType *OpTy = dyn_cast<VectorType>(CurTy); |
3227 | if (Record.size() < 3 || !OpTy) |
3228 | return error("Invalid shufflevector constexpr record"); |
3229 | V = BitcodeConstant::create( |
3230 | Alloc, CurTy, Instruction::ShuffleVector, |
3231 | {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]}); |
3232 | break; |
3233 | } |
3234 | case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] |
3235 | VectorType *RTy = dyn_cast<VectorType>(CurTy); |
3236 | VectorType *OpTy = |
3237 | dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); |
3238 | if (Record.size() < 4 || !RTy || !OpTy) |
3239 | return error("Invalid shufflevector constexpr record"); |
3240 | V = BitcodeConstant::create( |
3241 | Alloc, CurTy, Instruction::ShuffleVector, |
3242 | {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]}); |
3243 | break; |
3244 | } |
3245 | case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] |
3246 | if (Record.size() < 4) |
3247 | return error("Invalid cmp constexpt record"); |
3248 | unsigned OpTyID = Record[0]; |
3249 | Type *OpTy = getTypeByID(OpTyID); |
3250 | if (!OpTy) |
3251 | return error("Invalid cmp constexpr record"); |
3252 | V = BitcodeConstant::create( |
3253 | Alloc, CurTy, |
3254 | {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp |
3255 | : Instruction::ICmp), |
3256 | (uint8_t)Record[3]}, |
3257 | {(unsigned)Record[1], (unsigned)Record[2]}); |
3258 | break; |
3259 | } |
3260 | // This maintains backward compatibility, pre-asm dialect keywords. |
3261 | // Deprecated, but still needed to read old bitcode files. |
3262 | case bitc::CST_CODE_INLINEASM_OLD: { |
3263 | if (Record.size() < 2) |
3264 | return error("Invalid inlineasm record"); |
3265 | std::string AsmStr, ConstrStr; |
3266 | bool HasSideEffects = Record[0] & 1; |
3267 | bool IsAlignStack = Record[0] >> 1; |
3268 | unsigned AsmStrSize = Record[1]; |
3269 | if (2+AsmStrSize >= Record.size()) |
3270 | return error("Invalid inlineasm record"); |
3271 | unsigned ConstStrSize = Record[2+AsmStrSize]; |
3272 | if (3+AsmStrSize+ConstStrSize > Record.size()) |
3273 | return error("Invalid inlineasm record"); |
3274 | |
3275 | for (unsigned i = 0; i != AsmStrSize; ++i) |
3276 | AsmStr += (char)Record[2+i]; |
3277 | for (unsigned i = 0; i != ConstStrSize; ++i) |
3278 | ConstrStr += (char)Record[3+AsmStrSize+i]; |
3279 | UpgradeInlineAsmString(&AsmStr); |
3280 | if (!CurElemTy) |
3281 | return error("Missing element type for old-style inlineasm"); |
3282 | V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, |
3283 | HasSideEffects, IsAlignStack); |
3284 | break; |
3285 | } |
3286 | // This version adds support for the asm dialect keywords (e.g., |
3287 | // inteldialect). |
3288 | case bitc::CST_CODE_INLINEASM_OLD2: { |
3289 | if (Record.size() < 2) |
3290 | return error("Invalid inlineasm record"); |
3291 | std::string AsmStr, ConstrStr; |
3292 | bool HasSideEffects = Record[0] & 1; |
3293 | bool IsAlignStack = (Record[0] >> 1) & 1; |
3294 | unsigned AsmDialect = Record[0] >> 2; |
3295 | unsigned AsmStrSize = Record[1]; |
3296 | if (2+AsmStrSize >= Record.size()) |
3297 | return error("Invalid inlineasm record"); |
3298 | unsigned ConstStrSize = Record[2+AsmStrSize]; |
3299 | if (3+AsmStrSize+ConstStrSize > Record.size()) |
3300 | return error("Invalid inlineasm record"); |
3301 | |
3302 | for (unsigned i = 0; i != AsmStrSize; ++i) |
3303 | AsmStr += (char)Record[2+i]; |
3304 | for (unsigned i = 0; i != ConstStrSize; ++i) |
3305 | ConstrStr += (char)Record[3+AsmStrSize+i]; |
3306 | UpgradeInlineAsmString(&AsmStr); |
3307 | if (!CurElemTy) |
3308 | return error("Missing element type for old-style inlineasm"); |
3309 | V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, |
3310 | HasSideEffects, IsAlignStack, |
3311 | InlineAsm::AsmDialect(AsmDialect)); |
3312 | break; |
3313 | } |
3314 | // This version adds support for the unwind keyword. |
3315 | case bitc::CST_CODE_INLINEASM_OLD3: { |
3316 | if (Record.size() < 2) |
3317 | return error("Invalid inlineasm record"); |
3318 | unsigned OpNum = 0; |
3319 | std::string AsmStr, ConstrStr; |
3320 | bool HasSideEffects = Record[OpNum] & 1; |
3321 | bool IsAlignStack = (Record[OpNum] >> 1) & 1; |
3322 | unsigned AsmDialect = (Record[OpNum] >> 2) & 1; |
3323 | bool CanThrow = (Record[OpNum] >> 3) & 1; |
3324 | ++OpNum; |
3325 | unsigned AsmStrSize = Record[OpNum]; |
3326 | ++OpNum; |
3327 | if (OpNum + AsmStrSize >= Record.size()) |
3328 | return error("Invalid inlineasm record"); |
3329 | unsigned ConstStrSize = Record[OpNum + AsmStrSize]; |
3330 | if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) |
3331 | return error("Invalid inlineasm record"); |
3332 | |
3333 | for (unsigned i = 0; i != AsmStrSize; ++i) |
3334 | AsmStr += (char)Record[OpNum + i]; |
3335 | ++OpNum; |
3336 | for (unsigned i = 0; i != ConstStrSize; ++i) |
3337 | ConstrStr += (char)Record[OpNum + AsmStrSize + i]; |
3338 | UpgradeInlineAsmString(&AsmStr); |
3339 | if (!CurElemTy) |
3340 | return error("Missing element type for old-style inlineasm"); |
3341 | V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, |
3342 | HasSideEffects, IsAlignStack, |
3343 | InlineAsm::AsmDialect(AsmDialect), CanThrow); |
3344 | break; |
3345 | } |
3346 | // This version adds explicit function type. |
3347 | case bitc::CST_CODE_INLINEASM: { |
3348 | if (Record.size() < 3) |
3349 | return error("Invalid inlineasm record"); |
3350 | unsigned OpNum = 0; |
3351 | auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum])); |
3352 | ++OpNum; |
3353 | if (!FnTy) |
3354 | return error("Invalid inlineasm record"); |
3355 | std::string AsmStr, ConstrStr; |
3356 | bool HasSideEffects = Record[OpNum] & 1; |
3357 | bool IsAlignStack = (Record[OpNum] >> 1) & 1; |
3358 | unsigned AsmDialect = (Record[OpNum] >> 2) & 1; |
3359 | bool CanThrow = (Record[OpNum] >> 3) & 1; |
3360 | ++OpNum; |
3361 | unsigned AsmStrSize = Record[OpNum]; |
3362 | ++OpNum; |
3363 | if (OpNum + AsmStrSize >= Record.size()) |
3364 | return error("Invalid inlineasm record"); |
3365 | unsigned ConstStrSize = Record[OpNum + AsmStrSize]; |
3366 | if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) |
3367 | return error("Invalid inlineasm record"); |
3368 | |
3369 | for (unsigned i = 0; i != AsmStrSize; ++i) |
3370 | AsmStr += (char)Record[OpNum + i]; |
3371 | ++OpNum; |
3372 | for (unsigned i = 0; i != ConstStrSize; ++i) |
3373 | ConstrStr += (char)Record[OpNum + AsmStrSize + i]; |
3374 | UpgradeInlineAsmString(&AsmStr); |
3375 | V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack, |
3376 | InlineAsm::AsmDialect(AsmDialect), CanThrow); |
3377 | break; |
3378 | } |
3379 | case bitc::CST_CODE_BLOCKADDRESS:{ |
3380 | if (Record.size() < 3) |
3381 | return error("Invalid blockaddress record"); |
3382 | unsigned FnTyID = Record[0]; |
3383 | Type *FnTy = getTypeByID(FnTyID); |
3384 | if (!FnTy) |
3385 | return error("Invalid blockaddress record"); |
3386 | V = BitcodeConstant::create( |
3387 | Alloc, CurTy, |
3388 | {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]}, |
3389 | Record[1]); |
3390 | break; |
3391 | } |
3392 | case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: { |
3393 | if (Record.size() < 2) |
3394 | return error("Invalid dso_local record"); |
3395 | unsigned GVTyID = Record[0]; |
3396 | Type *GVTy = getTypeByID(GVTyID); |
3397 | if (!GVTy) |
3398 | return error("Invalid dso_local record"); |
3399 | V = BitcodeConstant::create( |
3400 | Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]); |
3401 | break; |
3402 | } |
3403 | case bitc::CST_CODE_NO_CFI_VALUE: { |
3404 | if (Record.size() < 2) |
3405 | return error("Invalid no_cfi record"); |
3406 | unsigned GVTyID = Record[0]; |
3407 | Type *GVTy = getTypeByID(GVTyID); |
3408 | if (!GVTy) |
3409 | return error("Invalid no_cfi record"); |
3410 | V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode, |
3411 | Record[1]); |
3412 | break; |
3413 | } |
3414 | } |
3415 | |
3416 | assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID")(static_cast <bool> (V->getType() == getTypeByID(CurTyID ) && "Incorrect result type ID") ? void (0) : __assert_fail ("V->getType() == getTypeByID(CurTyID) && \"Incorrect result type ID\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3416, __extension__ __PRETTY_FUNCTION__)); |
3417 | if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID)) |
3418 | return Err; |
3419 | ++NextCstNo; |
3420 | } |
3421 | } |
3422 | |
3423 | Error BitcodeReader::parseUseLists() { |
3424 | if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) |
3425 | return Err; |
3426 | |
3427 | // Read all the records. |
3428 | SmallVector<uint64_t, 64> Record; |
3429 | |
3430 | while (true) { |
3431 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
3432 | if (!MaybeEntry) |
3433 | return MaybeEntry.takeError(); |
3434 | BitstreamEntry Entry = MaybeEntry.get(); |
3435 | |
3436 | switch (Entry.Kind) { |
3437 | case BitstreamEntry::SubBlock: // Handled for us already. |
3438 | case BitstreamEntry::Error: |
3439 | return error("Malformed block"); |
3440 | case BitstreamEntry::EndBlock: |
3441 | return Error::success(); |
3442 | case BitstreamEntry::Record: |
3443 | // The interesting case. |
3444 | break; |
3445 | } |
3446 | |
3447 | // Read a use list record. |
3448 | Record.clear(); |
3449 | bool IsBB = false; |
3450 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
3451 | if (!MaybeRecord) |
3452 | return MaybeRecord.takeError(); |
3453 | switch (MaybeRecord.get()) { |
3454 | default: // Default behavior: unknown type. |
3455 | break; |
3456 | case bitc::USELIST_CODE_BB: |
3457 | IsBB = true; |
3458 | [[fallthrough]]; |
3459 | case bitc::USELIST_CODE_DEFAULT: { |
3460 | unsigned RecordLength = Record.size(); |
3461 | if (RecordLength < 3) |
3462 | // Records should have at least an ID and two indexes. |
3463 | return error("Invalid record"); |
3464 | unsigned ID = Record.pop_back_val(); |
3465 | |
3466 | Value *V; |
3467 | if (IsBB) { |
3468 | assert(ID < FunctionBBs.size() && "Basic block not found")(static_cast <bool> (ID < FunctionBBs.size() && "Basic block not found") ? void (0) : __assert_fail ("ID < FunctionBBs.size() && \"Basic block not found\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3468, __extension__ __PRETTY_FUNCTION__)); |
3469 | V = FunctionBBs[ID]; |
3470 | } else |
3471 | V = ValueList[ID]; |
3472 | unsigned NumUses = 0; |
3473 | SmallDenseMap<const Use *, unsigned, 16> Order; |
3474 | for (const Use &U : V->materialized_uses()) { |
3475 | if (++NumUses > Record.size()) |
3476 | break; |
3477 | Order[&U] = Record[NumUses - 1]; |
3478 | } |
3479 | if (Order.size() != Record.size() || NumUses > Record.size()) |
3480 | // Mismatches can happen if the functions are being materialized lazily |
3481 | // (out-of-order), or a value has been upgraded. |
3482 | break; |
3483 | |
3484 | V->sortUseList([&](const Use &L, const Use &R) { |
3485 | return Order.lookup(&L) < Order.lookup(&R); |
3486 | }); |
3487 | break; |
3488 | } |
3489 | } |
3490 | } |
3491 | } |
3492 | |
3493 | /// When we see the block for metadata, remember where it is and then skip it. |
3494 | /// This lets us lazily deserialize the metadata. |
3495 | Error BitcodeReader::rememberAndSkipMetadata() { |
3496 | // Save the current stream state. |
3497 | uint64_t CurBit = Stream.GetCurrentBitNo(); |
3498 | DeferredMetadataInfo.push_back(CurBit); |
3499 | |
3500 | // Skip over the block for now. |
3501 | if (Error Err = Stream.SkipBlock()) |
3502 | return Err; |
3503 | return Error::success(); |
3504 | } |
3505 | |
3506 | Error BitcodeReader::materializeMetadata() { |
3507 | for (uint64_t BitPos : DeferredMetadataInfo) { |
3508 | // Move the bit stream to the saved position. |
3509 | if (Error JumpFailed = Stream.JumpToBit(BitPos)) |
3510 | return JumpFailed; |
3511 | if (Error Err = MDLoader->parseModuleMetadata()) |
3512 | return Err; |
3513 | } |
3514 | |
3515 | // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level |
3516 | // metadata. Only upgrade if the new option doesn't exist to avoid upgrade |
3517 | // multiple times. |
3518 | if (!TheModule->getNamedMetadata("llvm.linker.options")) { |
3519 | if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) { |
3520 | NamedMDNode *LinkerOpts = |
3521 | TheModule->getOrInsertNamedMetadata("llvm.linker.options"); |
3522 | for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands()) |
3523 | LinkerOpts->addOperand(cast<MDNode>(MDOptions)); |
3524 | } |
3525 | } |
3526 | |
3527 | DeferredMetadataInfo.clear(); |
3528 | return Error::success(); |
3529 | } |
3530 | |
3531 | void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } |
3532 | |
3533 | /// When we see the block for a function body, remember where it is and then |
3534 | /// skip it. This lets us lazily deserialize the functions. |
3535 | Error BitcodeReader::rememberAndSkipFunctionBody() { |
3536 | // Get the function we are talking about. |
3537 | if (FunctionsWithBodies.empty()) |
3538 | return error("Insufficient function protos"); |
3539 | |
3540 | Function *Fn = FunctionsWithBodies.back(); |
3541 | FunctionsWithBodies.pop_back(); |
3542 | |
3543 | // Save the current stream state. |
3544 | uint64_t CurBit = Stream.GetCurrentBitNo(); |
3545 | assert((static_cast <bool> ((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo [Fn] == CurBit) && "Mismatch between VST and scanned function offsets" ) ? void (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3547, __extension__ __PRETTY_FUNCTION__)) |
3546 | (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&(static_cast <bool> ((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo [Fn] == CurBit) && "Mismatch between VST and scanned function offsets" ) ? void (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3547, __extension__ __PRETTY_FUNCTION__)) |
3547 | "Mismatch between VST and scanned function offsets")(static_cast <bool> ((DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo [Fn] == CurBit) && "Mismatch between VST and scanned function offsets" ) ? void (0) : __assert_fail ("(DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && \"Mismatch between VST and scanned function offsets\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3547, __extension__ __PRETTY_FUNCTION__)); |
3548 | DeferredFunctionInfo[Fn] = CurBit; |
3549 | |
3550 | // Skip over the function block for now. |
3551 | if (Error Err = Stream.SkipBlock()) |
3552 | return Err; |
3553 | return Error::success(); |
3554 | } |
3555 | |
3556 | Error BitcodeReader::globalCleanup() { |
3557 | // Patch the initializers for globals and aliases up. |
3558 | if (Error Err = resolveGlobalAndIndirectSymbolInits()) |
3559 | return Err; |
3560 | if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) |
3561 | return error("Malformed global initializer set"); |
3562 | |
3563 | // Look for intrinsic functions which need to be upgraded at some point |
3564 | // and functions that need to have their function attributes upgraded. |
3565 | for (Function &F : *TheModule) { |
3566 | MDLoader->upgradeDebugIntrinsics(F); |
3567 | Function *NewFn; |
3568 | if (UpgradeIntrinsicFunction(&F, NewFn)) |
3569 | UpgradedIntrinsics[&F] = NewFn; |
3570 | else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) |
3571 | // Some types could be renamed during loading if several modules are |
3572 | // loaded in the same LLVMContext (LTO scenario). In this case we should |
3573 | // remangle intrinsics names as well. |
3574 | RemangledIntrinsics[&F] = *Remangled; |
3575 | // Look for functions that rely on old function attribute behavior. |
3576 | UpgradeFunctionAttributes(F); |
3577 | } |
3578 | |
3579 | // Look for global variables which need to be renamed. |
3580 | std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables; |
3581 | for (GlobalVariable &GV : TheModule->globals()) |
3582 | if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV)) |
3583 | UpgradedVariables.emplace_back(&GV, Upgraded); |
3584 | for (auto &Pair : UpgradedVariables) { |
3585 | Pair.first->eraseFromParent(); |
3586 | TheModule->getGlobalList().push_back(Pair.second); |
3587 | } |
3588 | |
3589 | // Force deallocation of memory for these vectors to favor the client that |
3590 | // want lazy deserialization. |
3591 | std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits); |
3592 | std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits); |
3593 | return Error::success(); |
3594 | } |
3595 | |
3596 | /// Support for lazy parsing of function bodies. This is required if we |
3597 | /// either have an old bitcode file without a VST forward declaration record, |
3598 | /// or if we have an anonymous function being materialized, since anonymous |
3599 | /// functions do not have a name and are therefore not in the VST. |
3600 | Error BitcodeReader::rememberAndSkipFunctionBodies() { |
3601 | if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit)) |
3602 | return JumpFailed; |
3603 | |
3604 | if (Stream.AtEndOfStream()) |
3605 | return error("Could not find function in stream"); |
3606 | |
3607 | if (!SeenFirstFunctionBody) |
3608 | return error("Trying to materialize functions before seeing function blocks"); |
3609 | |
3610 | // An old bitcode file with the symbol table at the end would have |
3611 | // finished the parse greedily. |
3612 | assert(SeenValueSymbolTable)(static_cast <bool> (SeenValueSymbolTable) ? void (0) : __assert_fail ("SeenValueSymbolTable", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 3612, __extension__ __PRETTY_FUNCTION__)); |
3613 | |
3614 | SmallVector<uint64_t, 64> Record; |
3615 | |
3616 | while (true) { |
3617 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
3618 | if (!MaybeEntry) |
3619 | return MaybeEntry.takeError(); |
3620 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
3621 | |
3622 | switch (Entry.Kind) { |
3623 | default: |
3624 | return error("Expect SubBlock"); |
3625 | case BitstreamEntry::SubBlock: |
3626 | switch (Entry.ID) { |
3627 | default: |
3628 | return error("Expect function block"); |
3629 | case bitc::FUNCTION_BLOCK_ID: |
3630 | if (Error Err = rememberAndSkipFunctionBody()) |
3631 | return Err; |
3632 | NextUnreadBit = Stream.GetCurrentBitNo(); |
3633 | return Error::success(); |
3634 | } |
3635 | } |
3636 | } |
3637 | } |
3638 | |
3639 | Error BitcodeReaderBase::readBlockInfo() { |
3640 | Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo = |
3641 | Stream.ReadBlockInfoBlock(); |
3642 | if (!MaybeNewBlockInfo) |
3643 | return MaybeNewBlockInfo.takeError(); |
3644 | Optional<BitstreamBlockInfo> NewBlockInfo = |
3645 | std::move(MaybeNewBlockInfo.get()); |
3646 | if (!NewBlockInfo) |
3647 | return error("Malformed block"); |
3648 | BlockInfo = std::move(*NewBlockInfo); |
3649 | return Error::success(); |
3650 | } |
3651 | |
3652 | Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { |
3653 | // v1: [selection_kind, name] |
3654 | // v2: [strtab_offset, strtab_size, selection_kind] |
3655 | StringRef Name; |
3656 | std::tie(Name, Record) = readNameFromStrtab(Record); |
3657 | |
3658 | if (Record.empty()) |
3659 | return error("Invalid record"); |
3660 | Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); |
3661 | std::string OldFormatName; |
3662 | if (!UseStrtab) { |
3663 | if (Record.size() < 2) |
3664 | return error("Invalid record"); |
3665 | unsigned ComdatNameSize = Record[1]; |
3666 | if (ComdatNameSize > Record.size() - 2) |
3667 | return error("Comdat name size too large"); |
3668 | OldFormatName.reserve(ComdatNameSize); |
3669 | for (unsigned i = 0; i != ComdatNameSize; ++i) |
3670 | OldFormatName += (char)Record[2 + i]; |
3671 | Name = OldFormatName; |
3672 | } |
3673 | Comdat *C = TheModule->getOrInsertComdat(Name); |
3674 | C->setSelectionKind(SK); |
3675 | ComdatList.push_back(C); |
3676 | return Error::success(); |
3677 | } |
3678 | |
3679 | static void inferDSOLocal(GlobalValue *GV) { |
3680 | // infer dso_local from linkage and visibility if it is not encoded. |
3681 | if (GV->hasLocalLinkage() || |
3682 | (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())) |
3683 | GV->setDSOLocal(true); |
3684 | } |
3685 | |
3686 | GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) { |
3687 | GlobalValue::SanitizerMetadata Meta; |
3688 | if (V & (1 << 0)) |
3689 | Meta.NoAddress = true; |
3690 | if (V & (1 << 1)) |
3691 | Meta.NoHWAddress = true; |
3692 | if (V & (1 << 2)) |
3693 | Meta.Memtag = true; |
3694 | if (V & (1 << 3)) |
3695 | Meta.IsDynInit = true; |
3696 | return Meta; |
3697 | } |
3698 | |
3699 | Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { |
3700 | // v1: [pointer type, isconst, initid, linkage, alignment, section, |
3701 | // visibility, threadlocal, unnamed_addr, externally_initialized, |
3702 | // dllstorageclass, comdat, attributes, preemption specifier, |
3703 | // partition strtab offset, partition strtab size] (name in VST) |
3704 | // v2: [strtab_offset, strtab_size, v1] |
3705 | StringRef Name; |
3706 | std::tie(Name, Record) = readNameFromStrtab(Record); |
3707 | |
3708 | if (Record.size() < 6) |
3709 | return error("Invalid record"); |
3710 | unsigned TyID = Record[0]; |
3711 | Type *Ty = getTypeByID(TyID); |
3712 | if (!Ty) |
3713 | return error("Invalid record"); |
3714 | bool isConstant = Record[1] & 1; |
3715 | bool explicitType = Record[1] & 2; |
3716 | unsigned AddressSpace; |
3717 | if (explicitType) { |
3718 | AddressSpace = Record[1] >> 2; |
3719 | } else { |
3720 | if (!Ty->isPointerTy()) |
3721 | return error("Invalid type for value"); |
3722 | AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); |
3723 | TyID = getContainedTypeID(TyID); |
3724 | Ty = getTypeByID(TyID); |
3725 | if (!Ty) |
3726 | return error("Missing element type for old-style global"); |
3727 | } |
3728 | |
3729 | uint64_t RawLinkage = Record[3]; |
3730 | GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); |
3731 | MaybeAlign Alignment; |
3732 | if (Error Err = parseAlignmentValue(Record[4], Alignment)) |
3733 | return Err; |
3734 | std::string Section; |
3735 | if (Record[5]) { |
3736 | if (Record[5] - 1 >= SectionTable.size()) |
3737 | return error("Invalid ID"); |
3738 | Section = SectionTable[Record[5] - 1]; |
3739 | } |
3740 | GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; |
3741 | // Local linkage must have default visibility. |
3742 | // auto-upgrade `hidden` and `protected` for old bitcode. |
3743 | if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) |
3744 | Visibility = getDecodedVisibility(Record[6]); |
3745 | |
3746 | GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; |
3747 | if (Record.size() > 7) |
3748 | TLM = getDecodedThreadLocalMode(Record[7]); |
3749 | |
3750 | GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; |
3751 | if (Record.size() > 8) |
3752 | UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); |
3753 | |
3754 | bool ExternallyInitialized = false; |
3755 | if (Record.size() > 9) |
3756 | ExternallyInitialized = Record[9]; |
3757 | |
3758 | GlobalVariable *NewGV = |
3759 | new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name, |
3760 | nullptr, TLM, AddressSpace, ExternallyInitialized); |
3761 | NewGV->setAlignment(Alignment); |
3762 | if (!Section.empty()) |
3763 | NewGV->setSection(Section); |
3764 | NewGV->setVisibility(Visibility); |
3765 | NewGV->setUnnamedAddr(UnnamedAddr); |
3766 | |
3767 | if (Record.size() > 10) |
3768 | NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); |
3769 | else |
3770 | upgradeDLLImportExportLinkage(NewGV, RawLinkage); |
3771 | |
3772 | ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID)); |
3773 | |
3774 | // Remember which value to use for the global initializer. |
3775 | if (unsigned InitID = Record[2]) |
3776 | GlobalInits.push_back(std::make_pair(NewGV, InitID - 1)); |
3777 | |
3778 | if (Record.size() > 11) { |
3779 | if (unsigned ComdatID = Record[11]) { |
3780 | if (ComdatID > ComdatList.size()) |
3781 | return error("Invalid global variable comdat ID"); |
3782 | NewGV->setComdat(ComdatList[ComdatID - 1]); |
3783 | } |
3784 | } else if (hasImplicitComdat(RawLinkage)) { |
3785 | ImplicitComdatObjects.insert(NewGV); |
3786 | } |
3787 | |
3788 | if (Record.size() > 12) { |
3789 | auto AS = getAttributes(Record[12]).getFnAttrs(); |
3790 | NewGV->setAttributes(AS); |
3791 | } |
3792 | |
3793 | if (Record.size() > 13) { |
3794 | NewGV->setDSOLocal(getDecodedDSOLocal(Record[13])); |
3795 | } |
3796 | inferDSOLocal(NewGV); |
3797 | |
3798 | // Check whether we have enough values to read a partition name. |
3799 | if (Record.size() > 15) |
3800 | NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15])); |
3801 | |
3802 | if (Record.size() > 16 && Record[16]) { |
3803 | llvm::GlobalValue::SanitizerMetadata Meta = |
3804 | deserializeSanitizerMetadata(Record[16]); |
3805 | NewGV->setSanitizerMetadata(Meta); |
3806 | } |
3807 | |
3808 | return Error::success(); |
3809 | } |
3810 | |
3811 | Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) { |
3812 | // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section, |
3813 | // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat, |
3814 | // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST) |
3815 | // v2: [strtab_offset, strtab_size, v1] |
3816 | StringRef Name; |
3817 | std::tie(Name, Record) = readNameFromStrtab(Record); |
3818 | |
3819 | if (Record.size() < 8) |
3820 | return error("Invalid record"); |
3821 | unsigned FTyID = Record[0]; |
3822 | Type *FTy = getTypeByID(FTyID); |
3823 | if (!FTy) |
3824 | return error("Invalid record"); |
3825 | if (isa<PointerType>(FTy)) { |
3826 | FTyID = getContainedTypeID(FTyID, 0); |
3827 | FTy = getTypeByID(FTyID); |
3828 | if (!FTy) |
3829 | return error("Missing element type for old-style function"); |
3830 | } |
3831 | |
3832 | if (!isa<FunctionType>(FTy)) |
3833 | return error("Invalid type for value"); |
3834 | auto CC = static_cast<CallingConv::ID>(Record[1]); |
3835 | if (CC & ~CallingConv::MaxID) |
3836 | return error("Invalid calling convention ID"); |
3837 | |
3838 | unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace(); |
3839 | if (Record.size() > 16) |
3840 | AddrSpace = Record[16]; |
3841 | |
3842 | Function *Func = |
3843 | Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage, |
3844 | AddrSpace, Name, TheModule); |
3845 | |
3846 | assert(Func->getFunctionType() == FTy &&(static_cast <bool> (Func->getFunctionType() == FTy && "Incorrect fully specified type provided for function") ? void (0) : __assert_fail ("Func->getFunctionType() == FTy && \"Incorrect fully specified type provided for function\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3847, __extension__ __PRETTY_FUNCTION__)) |
3847 | "Incorrect fully specified type provided for function")(static_cast <bool> (Func->getFunctionType() == FTy && "Incorrect fully specified type provided for function") ? void (0) : __assert_fail ("Func->getFunctionType() == FTy && \"Incorrect fully specified type provided for function\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3847, __extension__ __PRETTY_FUNCTION__)); |
3848 | FunctionTypeIDs[Func] = FTyID; |
3849 | |
3850 | Func->setCallingConv(CC); |
3851 | bool isProto = Record[2]; |
3852 | uint64_t RawLinkage = Record[3]; |
3853 | Func->setLinkage(getDecodedLinkage(RawLinkage)); |
3854 | Func->setAttributes(getAttributes(Record[4])); |
3855 | |
3856 | // Upgrade any old-style byval or sret without a type by propagating the |
3857 | // argument's pointee type. There should be no opaque pointers where the byval |
3858 | // type is implicit. |
3859 | for (unsigned i = 0; i != Func->arg_size(); ++i) { |
3860 | for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, |
3861 | Attribute::InAlloca}) { |
3862 | if (!Func->hasParamAttribute(i, Kind)) |
3863 | continue; |
3864 | |
3865 | if (Func->getParamAttribute(i, Kind).getValueAsType()) |
3866 | continue; |
3867 | |
3868 | Func->removeParamAttr(i, Kind); |
3869 | |
3870 | unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1); |
3871 | Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID); |
3872 | if (!PtrEltTy) |
3873 | return error("Missing param element type for attribute upgrade"); |
3874 | |
3875 | Attribute NewAttr; |
3876 | switch (Kind) { |
3877 | case Attribute::ByVal: |
3878 | NewAttr = Attribute::getWithByValType(Context, PtrEltTy); |
3879 | break; |
3880 | case Attribute::StructRet: |
3881 | NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); |
3882 | break; |
3883 | case Attribute::InAlloca: |
3884 | NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); |
3885 | break; |
3886 | default: |
3887 | llvm_unreachable("not an upgraded type attribute")::llvm::llvm_unreachable_internal("not an upgraded type attribute" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 3887); |
3888 | } |
3889 | |
3890 | Func->addParamAttr(i, NewAttr); |
3891 | } |
3892 | } |
3893 | |
3894 | if (Func->getCallingConv() == CallingConv::X86_INTR && |
3895 | !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) { |
3896 | unsigned ParamTypeID = getContainedTypeID(FTyID, 1); |
3897 | Type *ByValTy = getPtrElementTypeByID(ParamTypeID); |
3898 | if (!ByValTy) |
3899 | return error("Missing param element type for x86_intrcc upgrade"); |
3900 | Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy); |
3901 | Func->addParamAttr(0, NewAttr); |
3902 | } |
3903 | |
3904 | MaybeAlign Alignment; |
3905 | if (Error Err = parseAlignmentValue(Record[5], Alignment)) |
3906 | return Err; |
3907 | Func->setAlignment(Alignment); |
3908 | if (Record[6]) { |
3909 | if (Record[6] - 1 >= SectionTable.size()) |
3910 | return error("Invalid ID"); |
3911 | Func->setSection(SectionTable[Record[6] - 1]); |
3912 | } |
3913 | // Local linkage must have default visibility. |
3914 | // auto-upgrade `hidden` and `protected` for old bitcode. |
3915 | if (!Func->hasLocalLinkage()) |
3916 | Func->setVisibility(getDecodedVisibility(Record[7])); |
3917 | if (Record.size() > 8 && Record[8]) { |
3918 | if (Record[8] - 1 >= GCTable.size()) |
3919 | return error("Invalid ID"); |
3920 | Func->setGC(GCTable[Record[8] - 1]); |
3921 | } |
3922 | GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; |
3923 | if (Record.size() > 9) |
3924 | UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); |
3925 | Func->setUnnamedAddr(UnnamedAddr); |
3926 | |
3927 | FunctionOperandInfo OperandInfo = {Func, 0, 0, 0}; |
3928 | if (Record.size() > 10) |
3929 | OperandInfo.Prologue = Record[10]; |
3930 | |
3931 | if (Record.size() > 11) |
3932 | Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); |
3933 | else |
3934 | upgradeDLLImportExportLinkage(Func, RawLinkage); |
3935 | |
3936 | if (Record.size() > 12) { |
3937 | if (unsigned ComdatID = Record[12]) { |
3938 | if (ComdatID > ComdatList.size()) |
3939 | return error("Invalid function comdat ID"); |
3940 | Func->setComdat(ComdatList[ComdatID - 1]); |
3941 | } |
3942 | } else if (hasImplicitComdat(RawLinkage)) { |
3943 | ImplicitComdatObjects.insert(Func); |
3944 | } |
3945 | |
3946 | if (Record.size() > 13) |
3947 | OperandInfo.Prefix = Record[13]; |
3948 | |
3949 | if (Record.size() > 14) |
3950 | OperandInfo.PersonalityFn = Record[14]; |
3951 | |
3952 | if (Record.size() > 15) { |
3953 | Func->setDSOLocal(getDecodedDSOLocal(Record[15])); |
3954 | } |
3955 | inferDSOLocal(Func); |
3956 | |
3957 | // Record[16] is the address space number. |
3958 | |
3959 | // Check whether we have enough values to read a partition name. Also make |
3960 | // sure Strtab has enough values. |
3961 | if (Record.size() > 18 && Strtab.data() && |
3962 | Record[17] + Record[18] <= Strtab.size()) { |
3963 | Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18])); |
3964 | } |
3965 | |
3966 | ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID)); |
3967 | |
3968 | if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue) |
3969 | FunctionOperands.push_back(OperandInfo); |
3970 | |
3971 | // If this is a function with a body, remember the prototype we are |
3972 | // creating now, so that we can match up the body with them later. |
3973 | if (!isProto) { |
3974 | Func->setIsMaterializable(true); |
3975 | FunctionsWithBodies.push_back(Func); |
3976 | DeferredFunctionInfo[Func] = 0; |
3977 | } |
3978 | return Error::success(); |
3979 | } |
3980 | |
3981 | Error BitcodeReader::parseGlobalIndirectSymbolRecord( |
3982 | unsigned BitCode, ArrayRef<uint64_t> Record) { |
3983 | // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST) |
3984 | // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, |
3985 | // dllstorageclass, threadlocal, unnamed_addr, |
3986 | // preemption specifier] (name in VST) |
3987 | // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage, |
3988 | // visibility, dllstorageclass, threadlocal, unnamed_addr, |
3989 | // preemption specifier] (name in VST) |
3990 | // v2: [strtab_offset, strtab_size, v1] |
3991 | StringRef Name; |
3992 | std::tie(Name, Record) = readNameFromStrtab(Record); |
3993 | |
3994 | bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; |
3995 | if (Record.size() < (3 + (unsigned)NewRecord)) |
3996 | return error("Invalid record"); |
3997 | unsigned OpNum = 0; |
3998 | unsigned TypeID = Record[OpNum++]; |
3999 | Type *Ty = getTypeByID(TypeID); |
4000 | if (!Ty) |
4001 | return error("Invalid record"); |
4002 | |
4003 | unsigned AddrSpace; |
4004 | if (!NewRecord) { |
4005 | auto *PTy = dyn_cast<PointerType>(Ty); |
4006 | if (!PTy) |
4007 | return error("Invalid type for value"); |
4008 | AddrSpace = PTy->getAddressSpace(); |
4009 | TypeID = getContainedTypeID(TypeID); |
4010 | Ty = getTypeByID(TypeID); |
4011 | if (!Ty) |
4012 | return error("Missing element type for old-style indirect symbol"); |
4013 | } else { |
4014 | AddrSpace = Record[OpNum++]; |
4015 | } |
4016 | |
4017 | auto Val = Record[OpNum++]; |
4018 | auto Linkage = Record[OpNum++]; |
4019 | GlobalValue *NewGA; |
4020 | if (BitCode == bitc::MODULE_CODE_ALIAS || |
4021 | BitCode == bitc::MODULE_CODE_ALIAS_OLD) |
4022 | NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, |
4023 | TheModule); |
4024 | else |
4025 | NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, |
4026 | nullptr, TheModule); |
4027 | |
4028 | // Local linkage must have default visibility. |
4029 | // auto-upgrade `hidden` and `protected` for old bitcode. |
4030 | if (OpNum != Record.size()) { |
4031 | auto VisInd = OpNum++; |
4032 | if (!NewGA->hasLocalLinkage()) |
4033 | NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); |
4034 | } |
4035 | if (BitCode == bitc::MODULE_CODE_ALIAS || |
4036 | BitCode == bitc::MODULE_CODE_ALIAS_OLD) { |
4037 | if (OpNum != Record.size()) |
4038 | NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); |
4039 | else |
4040 | upgradeDLLImportExportLinkage(NewGA, Linkage); |
4041 | if (OpNum != Record.size()) |
4042 | NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); |
4043 | if (OpNum != Record.size()) |
4044 | NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); |
4045 | } |
4046 | if (OpNum != Record.size()) |
4047 | NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++])); |
4048 | inferDSOLocal(NewGA); |
4049 | |
4050 | // Check whether we have enough values to read a partition name. |
4051 | if (OpNum + 1 < Record.size()) { |
4052 | NewGA->setPartition( |
4053 | StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1])); |
4054 | OpNum += 2; |
Value stored to 'OpNum' is never read | |
4055 | } |
4056 | |
4057 | ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID)); |
4058 | IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); |
4059 | return Error::success(); |
4060 | } |
4061 | |
4062 | Error BitcodeReader::parseModule(uint64_t ResumeBit, |
4063 | bool ShouldLazyLoadMetadata, |
4064 | DataLayoutCallbackTy DataLayoutCallback) { |
4065 | if (ResumeBit) { |
4066 | if (Error JumpFailed = Stream.JumpToBit(ResumeBit)) |
4067 | return JumpFailed; |
4068 | } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) |
4069 | return Err; |
4070 | |
4071 | SmallVector<uint64_t, 64> Record; |
4072 | |
4073 | // Parts of bitcode parsing depend on the datalayout. Make sure we |
4074 | // finalize the datalayout before we run any of that code. |
4075 | bool ResolvedDataLayout = false; |
4076 | auto ResolveDataLayout = [&] { |
4077 | if (ResolvedDataLayout) |
4078 | return; |
4079 | |
4080 | // datalayout and triple can't be parsed after this point. |
4081 | ResolvedDataLayout = true; |
4082 | |
4083 | // Upgrade data layout string. |
4084 | std::string DL = llvm::UpgradeDataLayoutString( |
4085 | TheModule->getDataLayoutStr(), TheModule->getTargetTriple()); |
4086 | TheModule->setDataLayout(DL); |
4087 | |
4088 | if (auto LayoutOverride = |
4089 | DataLayoutCallback(TheModule->getTargetTriple())) |
4090 | TheModule->setDataLayout(*LayoutOverride); |
4091 | }; |
4092 | |
4093 | // Read all the records for this module. |
4094 | while (true) { |
4095 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
4096 | if (!MaybeEntry) |
4097 | return MaybeEntry.takeError(); |
4098 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
4099 | |
4100 | switch (Entry.Kind) { |
4101 | case BitstreamEntry::Error: |
4102 | return error("Malformed block"); |
4103 | case BitstreamEntry::EndBlock: |
4104 | ResolveDataLayout(); |
4105 | return globalCleanup(); |
4106 | |
4107 | case BitstreamEntry::SubBlock: |
4108 | switch (Entry.ID) { |
4109 | default: // Skip unknown content. |
4110 | if (Error Err = Stream.SkipBlock()) |
4111 | return Err; |
4112 | break; |
4113 | case bitc::BLOCKINFO_BLOCK_ID: |
4114 | if (Error Err = readBlockInfo()) |
4115 | return Err; |
4116 | break; |
4117 | case bitc::PARAMATTR_BLOCK_ID: |
4118 | if (Error Err = parseAttributeBlock()) |
4119 | return Err; |
4120 | break; |
4121 | case bitc::PARAMATTR_GROUP_BLOCK_ID: |
4122 | if (Error Err = parseAttributeGroupBlock()) |
4123 | return Err; |
4124 | break; |
4125 | case bitc::TYPE_BLOCK_ID_NEW: |
4126 | if (Error Err = parseTypeTable()) |
4127 | return Err; |
4128 | break; |
4129 | case bitc::VALUE_SYMTAB_BLOCK_ID: |
4130 | if (!SeenValueSymbolTable) { |
4131 | // Either this is an old form VST without function index and an |
4132 | // associated VST forward declaration record (which would have caused |
4133 | // the VST to be jumped to and parsed before it was encountered |
4134 | // normally in the stream), or there were no function blocks to |
4135 | // trigger an earlier parsing of the VST. |
4136 | assert(VSTOffset == 0 || FunctionsWithBodies.empty())(static_cast <bool> (VSTOffset == 0 || FunctionsWithBodies .empty()) ? void (0) : __assert_fail ("VSTOffset == 0 || FunctionsWithBodies.empty()" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4136, __extension__ __PRETTY_FUNCTION__)); |
4137 | if (Error Err = parseValueSymbolTable()) |
4138 | return Err; |
4139 | SeenValueSymbolTable = true; |
4140 | } else { |
4141 | // We must have had a VST forward declaration record, which caused |
4142 | // the parser to jump to and parse the VST earlier. |
4143 | assert(VSTOffset > 0)(static_cast <bool> (VSTOffset > 0) ? void (0) : __assert_fail ("VSTOffset > 0", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 4143, __extension__ __PRETTY_FUNCTION__)); |
4144 | if (Error Err = Stream.SkipBlock()) |
4145 | return Err; |
4146 | } |
4147 | break; |
4148 | case bitc::CONSTANTS_BLOCK_ID: |
4149 | if (Error Err = parseConstants()) |
4150 | return Err; |
4151 | if (Error Err = resolveGlobalAndIndirectSymbolInits()) |
4152 | return Err; |
4153 | break; |
4154 | case bitc::METADATA_BLOCK_ID: |
4155 | if (ShouldLazyLoadMetadata) { |
4156 | if (Error Err = rememberAndSkipMetadata()) |
4157 | return Err; |
4158 | break; |
4159 | } |
4160 | assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata")(static_cast <bool> (DeferredMetadataInfo.empty() && "Unexpected deferred metadata") ? void (0) : __assert_fail ( "DeferredMetadataInfo.empty() && \"Unexpected deferred metadata\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4160, __extension__ __PRETTY_FUNCTION__)); |
4161 | if (Error Err = MDLoader->parseModuleMetadata()) |
4162 | return Err; |
4163 | break; |
4164 | case bitc::METADATA_KIND_BLOCK_ID: |
4165 | if (Error Err = MDLoader->parseMetadataKinds()) |
4166 | return Err; |
4167 | break; |
4168 | case bitc::FUNCTION_BLOCK_ID: |
4169 | ResolveDataLayout(); |
4170 | |
4171 | // If this is the first function body we've seen, reverse the |
4172 | // FunctionsWithBodies list. |
4173 | if (!SeenFirstFunctionBody) { |
4174 | std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); |
4175 | if (Error Err = globalCleanup()) |
4176 | return Err; |
4177 | SeenFirstFunctionBody = true; |
4178 | } |
4179 | |
4180 | if (VSTOffset > 0) { |
4181 | // If we have a VST forward declaration record, make sure we |
4182 | // parse the VST now if we haven't already. It is needed to |
4183 | // set up the DeferredFunctionInfo vector for lazy reading. |
4184 | if (!SeenValueSymbolTable) { |
4185 | if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset)) |
4186 | return Err; |
4187 | SeenValueSymbolTable = true; |
4188 | // Fall through so that we record the NextUnreadBit below. |
4189 | // This is necessary in case we have an anonymous function that |
4190 | // is later materialized. Since it will not have a VST entry we |
4191 | // need to fall back to the lazy parse to find its offset. |
4192 | } else { |
4193 | // If we have a VST forward declaration record, but have already |
4194 | // parsed the VST (just above, when the first function body was |
4195 | // encountered here), then we are resuming the parse after |
4196 | // materializing functions. The ResumeBit points to the |
4197 | // start of the last function block recorded in the |
4198 | // DeferredFunctionInfo map. Skip it. |
4199 | if (Error Err = Stream.SkipBlock()) |
4200 | return Err; |
4201 | continue; |
4202 | } |
4203 | } |
4204 | |
4205 | // Support older bitcode files that did not have the function |
4206 | // index in the VST, nor a VST forward declaration record, as |
4207 | // well as anonymous functions that do not have VST entries. |
4208 | // Build the DeferredFunctionInfo vector on the fly. |
4209 | if (Error Err = rememberAndSkipFunctionBody()) |
4210 | return Err; |
4211 | |
4212 | // Suspend parsing when we reach the function bodies. Subsequent |
4213 | // materialization calls will resume it when necessary. If the bitcode |
4214 | // file is old, the symbol table will be at the end instead and will not |
4215 | // have been seen yet. In this case, just finish the parse now. |
4216 | if (SeenValueSymbolTable) { |
4217 | NextUnreadBit = Stream.GetCurrentBitNo(); |
4218 | // After the VST has been parsed, we need to make sure intrinsic name |
4219 | // are auto-upgraded. |
4220 | return globalCleanup(); |
4221 | } |
4222 | break; |
4223 | case bitc::USELIST_BLOCK_ID: |
4224 | if (Error Err = parseUseLists()) |
4225 | return Err; |
4226 | break; |
4227 | case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: |
4228 | if (Error Err = parseOperandBundleTags()) |
4229 | return Err; |
4230 | break; |
4231 | case bitc::SYNC_SCOPE_NAMES_BLOCK_ID: |
4232 | if (Error Err = parseSyncScopeNames()) |
4233 | return Err; |
4234 | break; |
4235 | } |
4236 | continue; |
4237 | |
4238 | case BitstreamEntry::Record: |
4239 | // The interesting case. |
4240 | break; |
4241 | } |
4242 | |
4243 | // Read a record. |
4244 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); |
4245 | if (!MaybeBitCode) |
4246 | return MaybeBitCode.takeError(); |
4247 | switch (unsigned BitCode = MaybeBitCode.get()) { |
4248 | default: break; // Default behavior, ignore unknown content. |
4249 | case bitc::MODULE_CODE_VERSION: { |
4250 | Expected<unsigned> VersionOrErr = parseVersionRecord(Record); |
4251 | if (!VersionOrErr) |
4252 | return VersionOrErr.takeError(); |
4253 | UseRelativeIDs = *VersionOrErr >= 1; |
4254 | break; |
4255 | } |
4256 | case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] |
4257 | if (ResolvedDataLayout) |
4258 | return error("target triple too late in module"); |
4259 | std::string S; |
4260 | if (convertToString(Record, 0, S)) |
4261 | return error("Invalid record"); |
4262 | TheModule->setTargetTriple(S); |
4263 | break; |
4264 | } |
4265 | case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] |
4266 | if (ResolvedDataLayout) |
4267 | return error("datalayout too late in module"); |
4268 | std::string S; |
4269 | if (convertToString(Record, 0, S)) |
4270 | return error("Invalid record"); |
4271 | Expected<DataLayout> MaybeDL = DataLayout::parse(S); |
4272 | if (!MaybeDL) |
4273 | return MaybeDL.takeError(); |
4274 | TheModule->setDataLayout(MaybeDL.get()); |
4275 | break; |
4276 | } |
4277 | case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] |
4278 | std::string S; |
4279 | if (convertToString(Record, 0, S)) |
4280 | return error("Invalid record"); |
4281 | TheModule->setModuleInlineAsm(S); |
4282 | break; |
4283 | } |
4284 | case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] |
4285 | // Deprecated, but still needed to read old bitcode files. |
4286 | std::string S; |
4287 | if (convertToString(Record, 0, S)) |
4288 | return error("Invalid record"); |
4289 | // Ignore value. |
4290 | break; |
4291 | } |
4292 | case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] |
4293 | std::string S; |
4294 | if (convertToString(Record, 0, S)) |
4295 | return error("Invalid record"); |
4296 | SectionTable.push_back(S); |
4297 | break; |
4298 | } |
4299 | case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] |
4300 | std::string S; |
4301 | if (convertToString(Record, 0, S)) |
4302 | return error("Invalid record"); |
4303 | GCTable.push_back(S); |
4304 | break; |
4305 | } |
4306 | case bitc::MODULE_CODE_COMDAT: |
4307 | if (Error Err = parseComdatRecord(Record)) |
4308 | return Err; |
4309 | break; |
4310 | // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC} |
4311 | // written by ThinLinkBitcodeWriter. See |
4312 | // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each |
4313 | // record |
4314 | // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714) |
4315 | case bitc::MODULE_CODE_GLOBALVAR: |
4316 | if (Error Err = parseGlobalVarRecord(Record)) |
4317 | return Err; |
4318 | break; |
4319 | case bitc::MODULE_CODE_FUNCTION: |
4320 | ResolveDataLayout(); |
4321 | if (Error Err = parseFunctionRecord(Record)) |
4322 | return Err; |
4323 | break; |
4324 | case bitc::MODULE_CODE_IFUNC: |
4325 | case bitc::MODULE_CODE_ALIAS: |
4326 | case bitc::MODULE_CODE_ALIAS_OLD: |
4327 | if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record)) |
4328 | return Err; |
4329 | break; |
4330 | /// MODULE_CODE_VSTOFFSET: [offset] |
4331 | case bitc::MODULE_CODE_VSTOFFSET: |
4332 | if (Record.empty()) |
4333 | return error("Invalid record"); |
4334 | // Note that we subtract 1 here because the offset is relative to one word |
4335 | // before the start of the identification or module block, which was |
4336 | // historically always the start of the regular bitcode header. |
4337 | VSTOffset = Record[0] - 1; |
4338 | break; |
4339 | /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] |
4340 | case bitc::MODULE_CODE_SOURCE_FILENAME: |
4341 | SmallString<128> ValueName; |
4342 | if (convertToString(Record, 0, ValueName)) |
4343 | return error("Invalid record"); |
4344 | TheModule->setSourceFileName(ValueName); |
4345 | break; |
4346 | } |
4347 | Record.clear(); |
4348 | } |
4349 | } |
4350 | |
4351 | Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, |
4352 | bool IsImporting, |
4353 | DataLayoutCallbackTy DataLayoutCallback) { |
4354 | TheModule = M; |
4355 | MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, |
4356 | [&](unsigned ID) { return getTypeByID(ID); }); |
4357 | return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback); |
4358 | } |
4359 | |
4360 | Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { |
4361 | if (!isa<PointerType>(PtrType)) |
4362 | return error("Load/Store operand is not a pointer type"); |
4363 | |
4364 | if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType)) |
4365 | return error("Explicit load/store type does not match pointee " |
4366 | "type of pointer operand"); |
4367 | if (!PointerType::isLoadableOrStorableType(ValType)) |
4368 | return error("Cannot load/store from pointer"); |
4369 | return Error::success(); |
4370 | } |
4371 | |
4372 | Error BitcodeReader::propagateAttributeTypes(CallBase *CB, |
4373 | ArrayRef<unsigned> ArgTyIDs) { |
4374 | AttributeList Attrs = CB->getAttributes(); |
4375 | for (unsigned i = 0; i != CB->arg_size(); ++i) { |
4376 | for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, |
4377 | Attribute::InAlloca}) { |
4378 | if (!Attrs.hasParamAttr(i, Kind) || |
4379 | Attrs.getParamAttr(i, Kind).getValueAsType()) |
4380 | continue; |
4381 | |
4382 | Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]); |
4383 | if (!PtrEltTy) |
4384 | return error("Missing element type for typed attribute upgrade"); |
4385 | |
4386 | Attribute NewAttr; |
4387 | switch (Kind) { |
4388 | case Attribute::ByVal: |
4389 | NewAttr = Attribute::getWithByValType(Context, PtrEltTy); |
4390 | break; |
4391 | case Attribute::StructRet: |
4392 | NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); |
4393 | break; |
4394 | case Attribute::InAlloca: |
4395 | NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); |
4396 | break; |
4397 | default: |
4398 | llvm_unreachable("not an upgraded type attribute")::llvm::llvm_unreachable_internal("not an upgraded type attribute" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4398); |
4399 | } |
4400 | |
4401 | Attrs = Attrs.addParamAttribute(Context, i, NewAttr); |
4402 | } |
4403 | } |
4404 | |
4405 | if (CB->isInlineAsm()) { |
4406 | const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand()); |
4407 | unsigned ArgNo = 0; |
4408 | for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { |
4409 | if (!CI.hasArg()) |
4410 | continue; |
4411 | |
4412 | if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) { |
4413 | Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]); |
4414 | if (!ElemTy) |
4415 | return error("Missing element type for inline asm upgrade"); |
4416 | Attrs = Attrs.addParamAttribute( |
4417 | Context, ArgNo, |
4418 | Attribute::get(Context, Attribute::ElementType, ElemTy)); |
4419 | } |
4420 | |
4421 | ArgNo++; |
4422 | } |
4423 | } |
4424 | |
4425 | switch (CB->getIntrinsicID()) { |
4426 | case Intrinsic::preserve_array_access_index: |
4427 | case Intrinsic::preserve_struct_access_index: |
4428 | case Intrinsic::aarch64_ldaxr: |
4429 | case Intrinsic::aarch64_ldxr: |
4430 | case Intrinsic::aarch64_stlxr: |
4431 | case Intrinsic::aarch64_stxr: |
4432 | case Intrinsic::arm_ldaex: |
4433 | case Intrinsic::arm_ldrex: |
4434 | case Intrinsic::arm_stlex: |
4435 | case Intrinsic::arm_strex: { |
4436 | unsigned ArgNo; |
4437 | switch (CB->getIntrinsicID()) { |
4438 | case Intrinsic::aarch64_stlxr: |
4439 | case Intrinsic::aarch64_stxr: |
4440 | case Intrinsic::arm_stlex: |
4441 | case Intrinsic::arm_strex: |
4442 | ArgNo = 1; |
4443 | break; |
4444 | default: |
4445 | ArgNo = 0; |
4446 | break; |
4447 | } |
4448 | if (!Attrs.getParamElementType(ArgNo)) { |
4449 | Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]); |
4450 | if (!ElTy) |
4451 | return error("Missing element type for elementtype upgrade"); |
4452 | Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy); |
4453 | Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr); |
4454 | } |
4455 | break; |
4456 | } |
4457 | default: |
4458 | break; |
4459 | } |
4460 | |
4461 | CB->setAttributes(Attrs); |
4462 | return Error::success(); |
4463 | } |
4464 | |
4465 | /// Lazily parse the specified function body block. |
4466 | Error BitcodeReader::parseFunctionBody(Function *F) { |
4467 | if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) |
4468 | return Err; |
4469 | |
4470 | // Unexpected unresolved metadata when parsing function. |
4471 | if (MDLoader->hasFwdRefs()) |
4472 | return error("Invalid function metadata: incoming forward references"); |
4473 | |
4474 | InstructionList.clear(); |
4475 | unsigned ModuleValueListSize = ValueList.size(); |
4476 | unsigned ModuleMDLoaderSize = MDLoader->size(); |
4477 | |
4478 | // Add all the function arguments to the value table. |
4479 | unsigned ArgNo = 0; |
4480 | unsigned FTyID = FunctionTypeIDs[F]; |
4481 | for (Argument &I : F->args()) { |
4482 | unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1); |
4483 | assert(I.getType() == getTypeByID(ArgTyID) &&(static_cast <bool> (I.getType() == getTypeByID(ArgTyID ) && "Incorrect fully specified type for Function Argument" ) ? void (0) : __assert_fail ("I.getType() == getTypeByID(ArgTyID) && \"Incorrect fully specified type for Function Argument\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4484, __extension__ __PRETTY_FUNCTION__)) |
4484 | "Incorrect fully specified type for Function Argument")(static_cast <bool> (I.getType() == getTypeByID(ArgTyID ) && "Incorrect fully specified type for Function Argument" ) ? void (0) : __assert_fail ("I.getType() == getTypeByID(ArgTyID) && \"Incorrect fully specified type for Function Argument\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4484, __extension__ __PRETTY_FUNCTION__)); |
4485 | ValueList.push_back(&I, ArgTyID); |
4486 | ++ArgNo; |
4487 | } |
4488 | unsigned NextValueNo = ValueList.size(); |
4489 | BasicBlock *CurBB = nullptr; |
4490 | unsigned CurBBNo = 0; |
4491 | // Block into which constant expressions from phi nodes are materialized. |
4492 | BasicBlock *PhiConstExprBB = nullptr; |
4493 | // Edge blocks for phi nodes into which constant expressions have been |
4494 | // expanded. |
4495 | SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4> |
4496 | ConstExprEdgeBBs; |
4497 | |
4498 | DebugLoc LastLoc; |
4499 | auto getLastInstruction = [&]() -> Instruction * { |
4500 | if (CurBB && !CurBB->empty()) |
4501 | return &CurBB->back(); |
4502 | else if (CurBBNo && FunctionBBs[CurBBNo - 1] && |
4503 | !FunctionBBs[CurBBNo - 1]->empty()) |
4504 | return &FunctionBBs[CurBBNo - 1]->back(); |
4505 | return nullptr; |
4506 | }; |
4507 | |
4508 | std::vector<OperandBundleDef> OperandBundles; |
4509 | |
4510 | // Read all the records. |
4511 | SmallVector<uint64_t, 64> Record; |
4512 | |
4513 | while (true) { |
4514 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
4515 | if (!MaybeEntry) |
4516 | return MaybeEntry.takeError(); |
4517 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
4518 | |
4519 | switch (Entry.Kind) { |
4520 | case BitstreamEntry::Error: |
4521 | return error("Malformed block"); |
4522 | case BitstreamEntry::EndBlock: |
4523 | goto OutOfRecordLoop; |
4524 | |
4525 | case BitstreamEntry::SubBlock: |
4526 | switch (Entry.ID) { |
4527 | default: // Skip unknown content. |
4528 | if (Error Err = Stream.SkipBlock()) |
4529 | return Err; |
4530 | break; |
4531 | case bitc::CONSTANTS_BLOCK_ID: |
4532 | if (Error Err = parseConstants()) |
4533 | return Err; |
4534 | NextValueNo = ValueList.size(); |
4535 | break; |
4536 | case bitc::VALUE_SYMTAB_BLOCK_ID: |
4537 | if (Error Err = parseValueSymbolTable()) |
4538 | return Err; |
4539 | break; |
4540 | case bitc::METADATA_ATTACHMENT_ID: |
4541 | if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList)) |
4542 | return Err; |
4543 | break; |
4544 | case bitc::METADATA_BLOCK_ID: |
4545 | assert(DeferredMetadataInfo.empty() &&(static_cast <bool> (DeferredMetadataInfo.empty() && "Must read all module-level metadata before function-level") ? void (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Must read all module-level metadata before function-level\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4546, __extension__ __PRETTY_FUNCTION__)) |
4546 | "Must read all module-level metadata before function-level")(static_cast <bool> (DeferredMetadataInfo.empty() && "Must read all module-level metadata before function-level") ? void (0) : __assert_fail ("DeferredMetadataInfo.empty() && \"Must read all module-level metadata before function-level\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4546, __extension__ __PRETTY_FUNCTION__)); |
4547 | if (Error Err = MDLoader->parseFunctionMetadata()) |
4548 | return Err; |
4549 | break; |
4550 | case bitc::USELIST_BLOCK_ID: |
4551 | if (Error Err = parseUseLists()) |
4552 | return Err; |
4553 | break; |
4554 | } |
4555 | continue; |
4556 | |
4557 | case BitstreamEntry::Record: |
4558 | // The interesting case. |
4559 | break; |
4560 | } |
4561 | |
4562 | // Read a record. |
4563 | Record.clear(); |
4564 | Instruction *I = nullptr; |
4565 | unsigned ResTypeID = InvalidTypeID; |
4566 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); |
4567 | if (!MaybeBitCode) |
4568 | return MaybeBitCode.takeError(); |
4569 | switch (unsigned BitCode = MaybeBitCode.get()) { |
4570 | default: // Default behavior: reject |
4571 | return error("Invalid value"); |
4572 | case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] |
4573 | if (Record.empty() || Record[0] == 0) |
4574 | return error("Invalid record"); |
4575 | // Create all the basic blocks for the function. |
4576 | FunctionBBs.resize(Record[0]); |
4577 | |
4578 | // See if anything took the address of blocks in this function. |
4579 | auto BBFRI = BasicBlockFwdRefs.find(F); |
4580 | if (BBFRI == BasicBlockFwdRefs.end()) { |
4581 | for (BasicBlock *&BB : FunctionBBs) |
4582 | BB = BasicBlock::Create(Context, "", F); |
4583 | } else { |
4584 | auto &BBRefs = BBFRI->second; |
4585 | // Check for invalid basic block references. |
4586 | if (BBRefs.size() > FunctionBBs.size()) |
4587 | return error("Invalid ID"); |
4588 | assert(!BBRefs.empty() && "Unexpected empty array")(static_cast <bool> (!BBRefs.empty() && "Unexpected empty array" ) ? void (0) : __assert_fail ("!BBRefs.empty() && \"Unexpected empty array\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4588, __extension__ __PRETTY_FUNCTION__)); |
4589 | assert(!BBRefs.front() && "Invalid reference to entry block")(static_cast <bool> (!BBRefs.front() && "Invalid reference to entry block" ) ? void (0) : __assert_fail ("!BBRefs.front() && \"Invalid reference to entry block\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4589, __extension__ __PRETTY_FUNCTION__)); |
4590 | for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; |
4591 | ++I) |
4592 | if (I < RE && BBRefs[I]) { |
4593 | BBRefs[I]->insertInto(F); |
4594 | FunctionBBs[I] = BBRefs[I]; |
4595 | } else { |
4596 | FunctionBBs[I] = BasicBlock::Create(Context, "", F); |
4597 | } |
4598 | |
4599 | // Erase from the table. |
4600 | BasicBlockFwdRefs.erase(BBFRI); |
4601 | } |
4602 | |
4603 | CurBB = FunctionBBs[0]; |
4604 | continue; |
4605 | } |
4606 | |
4607 | case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...] |
4608 | // The record should not be emitted if it's an empty list. |
4609 | if (Record.empty()) |
4610 | return error("Invalid record"); |
4611 | // When we have the RARE case of a BlockAddress Constant that is not |
4612 | // scoped to the Function it refers to, we need to conservatively |
4613 | // materialize the referred to Function, regardless of whether or not |
4614 | // that Function will ultimately be linked, otherwise users of |
4615 | // BitcodeReader might start splicing out Function bodies such that we |
4616 | // might no longer be able to materialize the BlockAddress since the |
4617 | // BasicBlock (and entire body of the Function) the BlockAddress refers |
4618 | // to may have been moved. In the case that the user of BitcodeReader |
4619 | // decides ultimately not to link the Function body, materializing here |
4620 | // could be considered wasteful, but it's better than a deserialization |
4621 | // failure as described. This keeps BitcodeReader unaware of complex |
4622 | // linkage policy decisions such as those use by LTO, leaving those |
4623 | // decisions "one layer up." |
4624 | for (uint64_t ValID : Record) |
4625 | if (auto *F = dyn_cast<Function>(ValueList[ValID])) |
4626 | BackwardRefFunctions.push_back(F); |
4627 | else |
4628 | return error("Invalid record"); |
4629 | |
4630 | continue; |
4631 | |
4632 | case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN |
4633 | // This record indicates that the last instruction is at the same |
4634 | // location as the previous instruction with a location. |
4635 | I = getLastInstruction(); |
4636 | |
4637 | if (!I) |
4638 | return error("Invalid record"); |
4639 | I->setDebugLoc(LastLoc); |
4640 | I = nullptr; |
4641 | continue; |
4642 | |
4643 | case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] |
4644 | I = getLastInstruction(); |
4645 | if (!I || Record.size() < 4) |
4646 | return error("Invalid record"); |
4647 | |
4648 | unsigned Line = Record[0], Col = Record[1]; |
4649 | unsigned ScopeID = Record[2], IAID = Record[3]; |
4650 | bool isImplicitCode = Record.size() == 5 && Record[4]; |
4651 | |
4652 | MDNode *Scope = nullptr, *IA = nullptr; |
4653 | if (ScopeID) { |
4654 | Scope = dyn_cast_or_null<MDNode>( |
4655 | MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1)); |
4656 | if (!Scope) |
4657 | return error("Invalid record"); |
4658 | } |
4659 | if (IAID) { |
4660 | IA = dyn_cast_or_null<MDNode>( |
4661 | MDLoader->getMetadataFwdRefOrLoad(IAID - 1)); |
4662 | if (!IA) |
4663 | return error("Invalid record"); |
4664 | } |
4665 | LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA, |
4666 | isImplicitCode); |
4667 | I->setDebugLoc(LastLoc); |
4668 | I = nullptr; |
4669 | continue; |
4670 | } |
4671 | case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode] |
4672 | unsigned OpNum = 0; |
4673 | Value *LHS; |
4674 | unsigned TypeID; |
4675 | if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) || |
4676 | OpNum+1 > Record.size()) |
4677 | return error("Invalid record"); |
4678 | |
4679 | int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType()); |
4680 | if (Opc == -1) |
4681 | return error("Invalid record"); |
4682 | I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); |
4683 | ResTypeID = TypeID; |
4684 | InstructionList.push_back(I); |
4685 | if (OpNum < Record.size()) { |
4686 | if (isa<FPMathOperator>(I)) { |
4687 | FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); |
4688 | if (FMF.any()) |
4689 | I->setFastMathFlags(FMF); |
4690 | } |
4691 | } |
4692 | break; |
4693 | } |
4694 | case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] |
4695 | unsigned OpNum = 0; |
4696 | Value *LHS, *RHS; |
4697 | unsigned TypeID; |
4698 | if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) || |
4699 | popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS, |
4700 | CurBB) || |
4701 | OpNum+1 > Record.size()) |
4702 | return error("Invalid record"); |
4703 | |
4704 | int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); |
4705 | if (Opc == -1) |
4706 | return error("Invalid record"); |
4707 | I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); |
4708 | ResTypeID = TypeID; |
4709 | InstructionList.push_back(I); |
4710 | if (OpNum < Record.size()) { |
4711 | if (Opc == Instruction::Add || |
4712 | Opc == Instruction::Sub || |
4713 | Opc == Instruction::Mul || |
4714 | Opc == Instruction::Shl) { |
4715 | if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) |
4716 | cast<BinaryOperator>(I)->setHasNoSignedWrap(true); |
4717 | if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) |
4718 | cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); |
4719 | } else if (Opc == Instruction::SDiv || |
4720 | Opc == Instruction::UDiv || |
4721 | Opc == Instruction::LShr || |
4722 | Opc == Instruction::AShr) { |
4723 | if (Record[OpNum] & (1 << bitc::PEO_EXACT)) |
4724 | cast<BinaryOperator>(I)->setIsExact(true); |
4725 | } else if (isa<FPMathOperator>(I)) { |
4726 | FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); |
4727 | if (FMF.any()) |
4728 | I->setFastMathFlags(FMF); |
4729 | } |
4730 | |
4731 | } |
4732 | break; |
4733 | } |
4734 | case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] |
4735 | unsigned OpNum = 0; |
4736 | Value *Op; |
4737 | unsigned OpTypeID; |
4738 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || |
4739 | OpNum+2 != Record.size()) |
4740 | return error("Invalid record"); |
4741 | |
4742 | ResTypeID = Record[OpNum]; |
4743 | Type *ResTy = getTypeByID(ResTypeID); |
4744 | int Opc = getDecodedCastOpcode(Record[OpNum + 1]); |
4745 | if (Opc == -1 || !ResTy) |
4746 | return error("Invalid record"); |
4747 | Instruction *Temp = nullptr; |
4748 | if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { |
4749 | if (Temp) { |
4750 | InstructionList.push_back(Temp); |
4751 | assert(CurBB && "No current BB?")(static_cast <bool> (CurBB && "No current BB?") ? void (0) : __assert_fail ("CurBB && \"No current BB?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 4751, __extension__ __PRETTY_FUNCTION__)); |
4752 | CurBB->getInstList().push_back(Temp); |
4753 | } |
4754 | } else { |
4755 | auto CastOp = (Instruction::CastOps)Opc; |
4756 | if (!CastInst::castIsValid(CastOp, Op, ResTy)) |
4757 | return error("Invalid cast"); |
4758 | I = CastInst::Create(CastOp, Op, ResTy); |
4759 | } |
4760 | InstructionList.push_back(I); |
4761 | break; |
4762 | } |
4763 | case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: |
4764 | case bitc::FUNC_CODE_INST_GEP_OLD: |
4765 | case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] |
4766 | unsigned OpNum = 0; |
4767 | |
4768 | unsigned TyID; |
4769 | Type *Ty; |
4770 | bool InBounds; |
4771 | |
4772 | if (BitCode == bitc::FUNC_CODE_INST_GEP) { |
4773 | InBounds = Record[OpNum++]; |
4774 | TyID = Record[OpNum++]; |
4775 | Ty = getTypeByID(TyID); |
4776 | } else { |
4777 | InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; |
4778 | TyID = InvalidTypeID; |
4779 | Ty = nullptr; |
4780 | } |
4781 | |
4782 | Value *BasePtr; |
4783 | unsigned BasePtrTypeID; |
4784 | if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID, |
4785 | CurBB)) |
4786 | return error("Invalid record"); |
4787 | |
4788 | if (!Ty) { |
4789 | TyID = getContainedTypeID(BasePtrTypeID); |
4790 | if (BasePtr->getType()->isVectorTy()) |
4791 | TyID = getContainedTypeID(TyID); |
4792 | Ty = getTypeByID(TyID); |
4793 | } else if (!cast<PointerType>(BasePtr->getType()->getScalarType()) |
4794 | ->isOpaqueOrPointeeTypeMatches(Ty)) { |
4795 | return error( |
4796 | "Explicit gep type does not match pointee type of pointer operand"); |
4797 | } |
4798 | |
4799 | SmallVector<Value*, 16> GEPIdx; |
4800 | while (OpNum != Record.size()) { |
4801 | Value *Op; |
4802 | unsigned OpTypeID; |
4803 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) |
4804 | return error("Invalid record"); |
4805 | GEPIdx.push_back(Op); |
4806 | } |
4807 | |
4808 | I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); |
4809 | |
4810 | ResTypeID = TyID; |
4811 | if (cast<GEPOperator>(I)->getNumIndices() != 0) { |
4812 | auto GTI = std::next(gep_type_begin(I)); |
4813 | for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) { |
4814 | unsigned SubType = 0; |
4815 | if (GTI.isStruct()) { |
4816 | ConstantInt *IdxC = |
4817 | Idx->getType()->isVectorTy() |
4818 | ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue()) |
4819 | : cast<ConstantInt>(Idx); |
4820 | SubType = IdxC->getZExtValue(); |
4821 | } |
4822 | ResTypeID = getContainedTypeID(ResTypeID, SubType); |
4823 | ++GTI; |
4824 | } |
4825 | } |
4826 | |
4827 | // At this point ResTypeID is the result element type. We need a pointer |
4828 | // or vector of pointer to it. |
4829 | ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID); |
4830 | if (I->getType()->isVectorTy()) |
4831 | ResTypeID = getVirtualTypeID(I->getType(), ResTypeID); |
4832 | |
4833 | InstructionList.push_back(I); |
4834 | if (InBounds) |
4835 | cast<GetElementPtrInst>(I)->setIsInBounds(true); |
4836 | break; |
4837 | } |
4838 | |
4839 | case bitc::FUNC_CODE_INST_EXTRACTVAL: { |
4840 | // EXTRACTVAL: [opty, opval, n x indices] |
4841 | unsigned OpNum = 0; |
4842 | Value *Agg; |
4843 | unsigned AggTypeID; |
4844 | if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB)) |
4845 | return error("Invalid record"); |
4846 | Type *Ty = Agg->getType(); |
4847 | |
4848 | unsigned RecSize = Record.size(); |
4849 | if (OpNum == RecSize) |
4850 | return error("EXTRACTVAL: Invalid instruction with 0 indices"); |
4851 | |
4852 | SmallVector<unsigned, 4> EXTRACTVALIdx; |
4853 | ResTypeID = AggTypeID; |
4854 | for (; OpNum != RecSize; ++OpNum) { |
4855 | bool IsArray = Ty->isArrayTy(); |
4856 | bool IsStruct = Ty->isStructTy(); |
4857 | uint64_t Index = Record[OpNum]; |
4858 | |
4859 | if (!IsStruct && !IsArray) |
4860 | return error("EXTRACTVAL: Invalid type"); |
4861 | if ((unsigned)Index != Index) |
4862 | return error("Invalid value"); |
4863 | if (IsStruct && Index >= Ty->getStructNumElements()) |
4864 | return error("EXTRACTVAL: Invalid struct index"); |
4865 | if (IsArray && Index >= Ty->getArrayNumElements()) |
4866 | return error("EXTRACTVAL: Invalid array index"); |
4867 | EXTRACTVALIdx.push_back((unsigned)Index); |
4868 | |
4869 | if (IsStruct) { |
4870 | Ty = Ty->getStructElementType(Index); |
4871 | ResTypeID = getContainedTypeID(ResTypeID, Index); |
4872 | } else { |
4873 | Ty = Ty->getArrayElementType(); |
4874 | ResTypeID = getContainedTypeID(ResTypeID); |
4875 | } |
4876 | } |
4877 | |
4878 | I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); |
4879 | InstructionList.push_back(I); |
4880 | break; |
4881 | } |
4882 | |
4883 | case bitc::FUNC_CODE_INST_INSERTVAL: { |
4884 | // INSERTVAL: [opty, opval, opty, opval, n x indices] |
4885 | unsigned OpNum = 0; |
4886 | Value *Agg; |
4887 | unsigned AggTypeID; |
4888 | if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB)) |
4889 | return error("Invalid record"); |
4890 | Value *Val; |
4891 | unsigned ValTypeID; |
4892 | if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) |
4893 | return error("Invalid record"); |
4894 | |
4895 | unsigned RecSize = Record.size(); |
4896 | if (OpNum == RecSize) |
4897 | return error("INSERTVAL: Invalid instruction with 0 indices"); |
4898 | |
4899 | SmallVector<unsigned, 4> INSERTVALIdx; |
4900 | Type *CurTy = Agg->getType(); |
4901 | for (; OpNum != RecSize; ++OpNum) { |
4902 | bool IsArray = CurTy->isArrayTy(); |
4903 | bool IsStruct = CurTy->isStructTy(); |
4904 | uint64_t Index = Record[OpNum]; |
4905 | |
4906 | if (!IsStruct && !IsArray) |
4907 | return error("INSERTVAL: Invalid type"); |
4908 | if ((unsigned)Index != Index) |
4909 | return error("Invalid value"); |
4910 | if (IsStruct && Index >= CurTy->getStructNumElements()) |
4911 | return error("INSERTVAL: Invalid struct index"); |
4912 | if (IsArray && Index >= CurTy->getArrayNumElements()) |
4913 | return error("INSERTVAL: Invalid array index"); |
4914 | |
4915 | INSERTVALIdx.push_back((unsigned)Index); |
4916 | if (IsStruct) |
4917 | CurTy = CurTy->getStructElementType(Index); |
4918 | else |
4919 | CurTy = CurTy->getArrayElementType(); |
4920 | } |
4921 | |
4922 | if (CurTy != Val->getType()) |
4923 | return error("Inserted value type doesn't match aggregate type"); |
4924 | |
4925 | I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); |
4926 | ResTypeID = AggTypeID; |
4927 | InstructionList.push_back(I); |
4928 | break; |
4929 | } |
4930 | |
4931 | case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] |
4932 | // obsolete form of select |
4933 | // handles select i1 ... in old bitcode |
4934 | unsigned OpNum = 0; |
4935 | Value *TrueVal, *FalseVal, *Cond; |
4936 | unsigned TypeID; |
4937 | Type *CondType = Type::getInt1Ty(Context); |
4938 | if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID, |
4939 | CurBB) || |
4940 | popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID, |
4941 | FalseVal, CurBB) || |
4942 | popValue(Record, OpNum, NextValueNo, CondType, |
4943 | getVirtualTypeID(CondType), Cond, CurBB)) |
4944 | return error("Invalid record"); |
4945 | |
4946 | I = SelectInst::Create(Cond, TrueVal, FalseVal); |
4947 | ResTypeID = TypeID; |
4948 | InstructionList.push_back(I); |
4949 | break; |
4950 | } |
4951 | |
4952 | case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] |
4953 | // new form of select |
4954 | // handles select i1 or select [N x i1] |
4955 | unsigned OpNum = 0; |
4956 | Value *TrueVal, *FalseVal, *Cond; |
4957 | unsigned ValTypeID, CondTypeID; |
4958 | if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID, |
4959 | CurBB) || |
4960 | popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID, |
4961 | FalseVal, CurBB) || |
4962 | getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB)) |
4963 | return error("Invalid record"); |
4964 | |
4965 | // select condition can be either i1 or [N x i1] |
4966 | if (VectorType* vector_type = |
4967 | dyn_cast<VectorType>(Cond->getType())) { |
4968 | // expect <n x i1> |
4969 | if (vector_type->getElementType() != Type::getInt1Ty(Context)) |
4970 | return error("Invalid type for value"); |
4971 | } else { |
4972 | // expect i1 |
4973 | if (Cond->getType() != Type::getInt1Ty(Context)) |
4974 | return error("Invalid type for value"); |
4975 | } |
4976 | |
4977 | I = SelectInst::Create(Cond, TrueVal, FalseVal); |
4978 | ResTypeID = ValTypeID; |
4979 | InstructionList.push_back(I); |
4980 | if (OpNum < Record.size() && isa<FPMathOperator>(I)) { |
4981 | FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); |
4982 | if (FMF.any()) |
4983 | I->setFastMathFlags(FMF); |
4984 | } |
4985 | break; |
4986 | } |
4987 | |
4988 | case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] |
4989 | unsigned OpNum = 0; |
4990 | Value *Vec, *Idx; |
4991 | unsigned VecTypeID, IdxTypeID; |
4992 | if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) || |
4993 | getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB)) |
4994 | return error("Invalid record"); |
4995 | if (!Vec->getType()->isVectorTy()) |
4996 | return error("Invalid type for value"); |
4997 | I = ExtractElementInst::Create(Vec, Idx); |
4998 | ResTypeID = getContainedTypeID(VecTypeID); |
4999 | InstructionList.push_back(I); |
5000 | break; |
5001 | } |
5002 | |
5003 | case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] |
5004 | unsigned OpNum = 0; |
5005 | Value *Vec, *Elt, *Idx; |
5006 | unsigned VecTypeID, IdxTypeID; |
5007 | if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB)) |
5008 | return error("Invalid record"); |
5009 | if (!Vec->getType()->isVectorTy()) |
5010 | return error("Invalid type for value"); |
5011 | if (popValue(Record, OpNum, NextValueNo, |
5012 | cast<VectorType>(Vec->getType())->getElementType(), |
5013 | getContainedTypeID(VecTypeID), Elt, CurBB) || |
5014 | getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB)) |
5015 | return error("Invalid record"); |
5016 | I = InsertElementInst::Create(Vec, Elt, Idx); |
5017 | ResTypeID = VecTypeID; |
5018 | InstructionList.push_back(I); |
5019 | break; |
5020 | } |
5021 | |
5022 | case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] |
5023 | unsigned OpNum = 0; |
5024 | Value *Vec1, *Vec2, *Mask; |
5025 | unsigned Vec1TypeID; |
5026 | if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID, |
5027 | CurBB) || |
5028 | popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID, |
5029 | Vec2, CurBB)) |
5030 | return error("Invalid record"); |
5031 | |
5032 | unsigned MaskTypeID; |
5033 | if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB)) |
5034 | return error("Invalid record"); |
5035 | if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) |
5036 | return error("Invalid type for value"); |
5037 | |
5038 | I = new ShuffleVectorInst(Vec1, Vec2, Mask); |
5039 | ResTypeID = |
5040 | getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID)); |
5041 | InstructionList.push_back(I); |
5042 | break; |
5043 | } |
5044 | |
5045 | case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] |
5046 | // Old form of ICmp/FCmp returning bool |
5047 | // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were |
5048 | // both legal on vectors but had different behaviour. |
5049 | case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] |
5050 | // FCmp/ICmp returning bool or vector of bool |
5051 | |
5052 | unsigned OpNum = 0; |
5053 | Value *LHS, *RHS; |
5054 | unsigned LHSTypeID; |
5055 | if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) || |
5056 | popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS, |
5057 | CurBB)) |
5058 | return error("Invalid record"); |
5059 | |
5060 | if (OpNum >= Record.size()) |
5061 | return error( |
5062 | "Invalid record: operand number exceeded available operands"); |
5063 | |
5064 | unsigned PredVal = Record[OpNum]; |
5065 | bool IsFP = LHS->getType()->isFPOrFPVectorTy(); |
5066 | FastMathFlags FMF; |
5067 | if (IsFP && Record.size() > OpNum+1) |
5068 | FMF = getDecodedFastMathFlags(Record[++OpNum]); |
5069 | |
5070 | if (OpNum+1 != Record.size()) |
5071 | return error("Invalid record"); |
5072 | |
5073 | if (LHS->getType()->isFPOrFPVectorTy()) |
5074 | I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); |
5075 | else |
5076 | I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); |
5077 | |
5078 | ResTypeID = getVirtualTypeID(I->getType()->getScalarType()); |
5079 | if (LHS->getType()->isVectorTy()) |
5080 | ResTypeID = getVirtualTypeID(I->getType(), ResTypeID); |
5081 | |
5082 | if (FMF.any()) |
5083 | I->setFastMathFlags(FMF); |
5084 | InstructionList.push_back(I); |
5085 | break; |
5086 | } |
5087 | |
5088 | case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] |
5089 | { |
5090 | unsigned Size = Record.size(); |
5091 | if (Size == 0) { |
5092 | I = ReturnInst::Create(Context); |
5093 | InstructionList.push_back(I); |
5094 | break; |
5095 | } |
5096 | |
5097 | unsigned OpNum = 0; |
5098 | Value *Op = nullptr; |
5099 | unsigned OpTypeID; |
5100 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) |
5101 | return error("Invalid record"); |
5102 | if (OpNum != Record.size()) |
5103 | return error("Invalid record"); |
5104 | |
5105 | I = ReturnInst::Create(Context, Op); |
5106 | InstructionList.push_back(I); |
5107 | break; |
5108 | } |
5109 | case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] |
5110 | if (Record.size() != 1 && Record.size() != 3) |
5111 | return error("Invalid record"); |
5112 | BasicBlock *TrueDest = getBasicBlock(Record[0]); |
5113 | if (!TrueDest) |
5114 | return error("Invalid record"); |
5115 | |
5116 | if (Record.size() == 1) { |
5117 | I = BranchInst::Create(TrueDest); |
5118 | InstructionList.push_back(I); |
5119 | } |
5120 | else { |
5121 | BasicBlock *FalseDest = getBasicBlock(Record[1]); |
5122 | Type *CondType = Type::getInt1Ty(Context); |
5123 | Value *Cond = getValue(Record, 2, NextValueNo, CondType, |
5124 | getVirtualTypeID(CondType), CurBB); |
5125 | if (!FalseDest || !Cond) |
5126 | return error("Invalid record"); |
5127 | I = BranchInst::Create(TrueDest, FalseDest, Cond); |
5128 | InstructionList.push_back(I); |
5129 | } |
5130 | break; |
5131 | } |
5132 | case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] |
5133 | if (Record.size() != 1 && Record.size() != 2) |
5134 | return error("Invalid record"); |
5135 | unsigned Idx = 0; |
5136 | Type *TokenTy = Type::getTokenTy(Context); |
5137 | Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy, |
5138 | getVirtualTypeID(TokenTy), CurBB); |
5139 | if (!CleanupPad) |
5140 | return error("Invalid record"); |
5141 | BasicBlock *UnwindDest = nullptr; |
5142 | if (Record.size() == 2) { |
5143 | UnwindDest = getBasicBlock(Record[Idx++]); |
5144 | if (!UnwindDest) |
5145 | return error("Invalid record"); |
5146 | } |
5147 | |
5148 | I = CleanupReturnInst::Create(CleanupPad, UnwindDest); |
5149 | InstructionList.push_back(I); |
5150 | break; |
5151 | } |
5152 | case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] |
5153 | if (Record.size() != 2) |
5154 | return error("Invalid record"); |
5155 | unsigned Idx = 0; |
5156 | Type *TokenTy = Type::getTokenTy(Context); |
5157 | Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy, |
5158 | getVirtualTypeID(TokenTy), CurBB); |
5159 | if (!CatchPad) |
5160 | return error("Invalid record"); |
5161 | BasicBlock *BB = getBasicBlock(Record[Idx++]); |
5162 | if (!BB) |
5163 | return error("Invalid record"); |
5164 | |
5165 | I = CatchReturnInst::Create(CatchPad, BB); |
5166 | InstructionList.push_back(I); |
5167 | break; |
5168 | } |
5169 | case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] |
5170 | // We must have, at minimum, the outer scope and the number of arguments. |
5171 | if (Record.size() < 2) |
5172 | return error("Invalid record"); |
5173 | |
5174 | unsigned Idx = 0; |
5175 | |
5176 | Type *TokenTy = Type::getTokenTy(Context); |
5177 | Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy, |
5178 | getVirtualTypeID(TokenTy), CurBB); |
5179 | |
5180 | unsigned NumHandlers = Record[Idx++]; |
5181 | |
5182 | SmallVector<BasicBlock *, 2> Handlers; |
5183 | for (unsigned Op = 0; Op != NumHandlers; ++Op) { |
5184 | BasicBlock *BB = getBasicBlock(Record[Idx++]); |
5185 | if (!BB) |
5186 | return error("Invalid record"); |
5187 | Handlers.push_back(BB); |
5188 | } |
5189 | |
5190 | BasicBlock *UnwindDest = nullptr; |
5191 | if (Idx + 1 == Record.size()) { |
5192 | UnwindDest = getBasicBlock(Record[Idx++]); |
5193 | if (!UnwindDest) |
5194 | return error("Invalid record"); |
5195 | } |
5196 | |
5197 | if (Record.size() != Idx) |
5198 | return error("Invalid record"); |
5199 | |
5200 | auto *CatchSwitch = |
5201 | CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); |
5202 | for (BasicBlock *Handler : Handlers) |
5203 | CatchSwitch->addHandler(Handler); |
5204 | I = CatchSwitch; |
5205 | ResTypeID = getVirtualTypeID(I->getType()); |
5206 | InstructionList.push_back(I); |
5207 | break; |
5208 | } |
5209 | case bitc::FUNC_CODE_INST_CATCHPAD: |
5210 | case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] |
5211 | // We must have, at minimum, the outer scope and the number of arguments. |
5212 | if (Record.size() < 2) |
5213 | return error("Invalid record"); |
5214 | |
5215 | unsigned Idx = 0; |
5216 | |
5217 | Type *TokenTy = Type::getTokenTy(Context); |
5218 | Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy, |
5219 | getVirtualTypeID(TokenTy), CurBB); |
5220 | |
5221 | unsigned NumArgOperands = Record[Idx++]; |
5222 | |
5223 | SmallVector<Value *, 2> Args; |
5224 | for (unsigned Op = 0; Op != NumArgOperands; ++Op) { |
5225 | Value *Val; |
5226 | unsigned ValTypeID; |
5227 | if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr)) |
5228 | return error("Invalid record"); |
5229 | Args.push_back(Val); |
5230 | } |
5231 | |
5232 | if (Record.size() != Idx) |
5233 | return error("Invalid record"); |
5234 | |
5235 | if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) |
5236 | I = CleanupPadInst::Create(ParentPad, Args); |
5237 | else |
5238 | I = CatchPadInst::Create(ParentPad, Args); |
5239 | ResTypeID = getVirtualTypeID(I->getType()); |
5240 | InstructionList.push_back(I); |
5241 | break; |
5242 | } |
5243 | case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] |
5244 | // Check magic |
5245 | if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { |
5246 | // "New" SwitchInst format with case ranges. The changes to write this |
5247 | // format were reverted but we still recognize bitcode that uses it. |
5248 | // Hopefully someday we will have support for case ranges and can use |
5249 | // this format again. |
5250 | |
5251 | unsigned OpTyID = Record[1]; |
5252 | Type *OpTy = getTypeByID(OpTyID); |
5253 | unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); |
5254 | |
5255 | Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB); |
5256 | BasicBlock *Default = getBasicBlock(Record[3]); |
5257 | if (!OpTy || !Cond || !Default) |
5258 | return error("Invalid record"); |
5259 | |
5260 | unsigned NumCases = Record[4]; |
5261 | |
5262 | SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); |
5263 | InstructionList.push_back(SI); |
5264 | |
5265 | unsigned CurIdx = 5; |
5266 | for (unsigned i = 0; i != NumCases; ++i) { |
5267 | SmallVector<ConstantInt*, 1> CaseVals; |
5268 | unsigned NumItems = Record[CurIdx++]; |
5269 | for (unsigned ci = 0; ci != NumItems; ++ci) { |
5270 | bool isSingleNumber = Record[CurIdx++]; |
5271 | |
5272 | APInt Low; |
5273 | unsigned ActiveWords = 1; |
5274 | if (ValueBitWidth > 64) |
5275 | ActiveWords = Record[CurIdx++]; |
5276 | Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), |
5277 | ValueBitWidth); |
5278 | CurIdx += ActiveWords; |
5279 | |
5280 | if (!isSingleNumber) { |
5281 | ActiveWords = 1; |
5282 | if (ValueBitWidth > 64) |
5283 | ActiveWords = Record[CurIdx++]; |
5284 | APInt High = readWideAPInt( |
5285 | makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); |
5286 | CurIdx += ActiveWords; |
5287 | |
5288 | // FIXME: It is not clear whether values in the range should be |
5289 | // compared as signed or unsigned values. The partially |
5290 | // implemented changes that used this format in the past used |
5291 | // unsigned comparisons. |
5292 | for ( ; Low.ule(High); ++Low) |
5293 | CaseVals.push_back(ConstantInt::get(Context, Low)); |
5294 | } else |
5295 | CaseVals.push_back(ConstantInt::get(Context, Low)); |
5296 | } |
5297 | BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); |
5298 | for (ConstantInt *Cst : CaseVals) |
5299 | SI->addCase(Cst, DestBB); |
5300 | } |
5301 | I = SI; |
5302 | break; |
5303 | } |
5304 | |
5305 | // Old SwitchInst format without case ranges. |
5306 | |
5307 | if (Record.size() < 3 || (Record.size() & 1) == 0) |
5308 | return error("Invalid record"); |
5309 | unsigned OpTyID = Record[0]; |
5310 | Type *OpTy = getTypeByID(OpTyID); |
5311 | Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); |
5312 | BasicBlock *Default = getBasicBlock(Record[2]); |
5313 | if (!OpTy || !Cond || !Default) |
5314 | return error("Invalid record"); |
5315 | unsigned NumCases = (Record.size()-3)/2; |
5316 | SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); |
5317 | InstructionList.push_back(SI); |
5318 | for (unsigned i = 0, e = NumCases; i != e; ++i) { |
5319 | ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>( |
5320 | getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr)); |
5321 | BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); |
5322 | if (!CaseVal || !DestBB) { |
5323 | delete SI; |
5324 | return error("Invalid record"); |
5325 | } |
5326 | SI->addCase(CaseVal, DestBB); |
5327 | } |
5328 | I = SI; |
5329 | break; |
5330 | } |
5331 | case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] |
5332 | if (Record.size() < 2) |
5333 | return error("Invalid record"); |
5334 | unsigned OpTyID = Record[0]; |
5335 | Type *OpTy = getTypeByID(OpTyID); |
5336 | Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); |
5337 | if (!OpTy || !Address) |
5338 | return error("Invalid record"); |
5339 | unsigned NumDests = Record.size()-2; |
5340 | IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); |
5341 | InstructionList.push_back(IBI); |
5342 | for (unsigned i = 0, e = NumDests; i != e; ++i) { |
5343 | if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { |
5344 | IBI->addDestination(DestBB); |
5345 | } else { |
5346 | delete IBI; |
5347 | return error("Invalid record"); |
5348 | } |
5349 | } |
5350 | I = IBI; |
5351 | break; |
5352 | } |
5353 | |
5354 | case bitc::FUNC_CODE_INST_INVOKE: { |
5355 | // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] |
5356 | if (Record.size() < 4) |
5357 | return error("Invalid record"); |
5358 | unsigned OpNum = 0; |
5359 | AttributeList PAL = getAttributes(Record[OpNum++]); |
5360 | unsigned CCInfo = Record[OpNum++]; |
5361 | BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); |
5362 | BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); |
5363 | |
5364 | unsigned FTyID = InvalidTypeID; |
5365 | FunctionType *FTy = nullptr; |
5366 | if ((CCInfo >> 13) & 1) { |
5367 | FTyID = Record[OpNum++]; |
5368 | FTy = dyn_cast<FunctionType>(getTypeByID(FTyID)); |
5369 | if (!FTy) |
5370 | return error("Explicit invoke type is not a function type"); |
5371 | } |
5372 | |
5373 | Value *Callee; |
5374 | unsigned CalleeTypeID; |
5375 | if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, |
5376 | CurBB)) |
5377 | return error("Invalid record"); |
5378 | |
5379 | PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); |
5380 | if (!CalleeTy) |
5381 | return error("Callee is not a pointer"); |
5382 | if (!FTy) { |
5383 | FTyID = getContainedTypeID(CalleeTypeID); |
5384 | FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); |
5385 | if (!FTy) |
5386 | return error("Callee is not of pointer to function type"); |
5387 | } else if (!CalleeTy->isOpaqueOrPointeeTypeMatches(FTy)) |
5388 | return error("Explicit invoke type does not match pointee type of " |
5389 | "callee operand"); |
5390 | if (Record.size() < FTy->getNumParams() + OpNum) |
5391 | return error("Insufficient operands to call"); |
5392 | |
5393 | SmallVector<Value*, 16> Ops; |
5394 | SmallVector<unsigned, 16> ArgTyIDs; |
5395 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { |
5396 | unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); |
5397 | Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i), |
5398 | ArgTyID, CurBB)); |
5399 | ArgTyIDs.push_back(ArgTyID); |
5400 | if (!Ops.back()) |
5401 | return error("Invalid record"); |
5402 | } |
5403 | |
5404 | if (!FTy->isVarArg()) { |
5405 | if (Record.size() != OpNum) |
5406 | return error("Invalid record"); |
5407 | } else { |
5408 | // Read type/value pairs for varargs params. |
5409 | while (OpNum != Record.size()) { |
5410 | Value *Op; |
5411 | unsigned OpTypeID; |
5412 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) |
5413 | return error("Invalid record"); |
5414 | Ops.push_back(Op); |
5415 | ArgTyIDs.push_back(OpTypeID); |
5416 | } |
5417 | } |
5418 | |
5419 | // Upgrade the bundles if needed. |
5420 | if (!OperandBundles.empty()) |
5421 | UpgradeOperandBundles(OperandBundles); |
5422 | |
5423 | I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops, |
5424 | OperandBundles); |
5425 | ResTypeID = getContainedTypeID(FTyID); |
5426 | OperandBundles.clear(); |
5427 | InstructionList.push_back(I); |
5428 | cast<InvokeInst>(I)->setCallingConv( |
5429 | static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); |
5430 | cast<InvokeInst>(I)->setAttributes(PAL); |
5431 | if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { |
5432 | I->deleteValue(); |
5433 | return Err; |
5434 | } |
5435 | |
5436 | break; |
5437 | } |
5438 | case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] |
5439 | unsigned Idx = 0; |
5440 | Value *Val = nullptr; |
5441 | unsigned ValTypeID; |
5442 | if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB)) |
5443 | return error("Invalid record"); |
5444 | I = ResumeInst::Create(Val); |
5445 | InstructionList.push_back(I); |
5446 | break; |
5447 | } |
5448 | case bitc::FUNC_CODE_INST_CALLBR: { |
5449 | // CALLBR: [attr, cc, norm, transfs, fty, fnid, args] |
5450 | unsigned OpNum = 0; |
5451 | AttributeList PAL = getAttributes(Record[OpNum++]); |
5452 | unsigned CCInfo = Record[OpNum++]; |
5453 | |
5454 | BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]); |
5455 | unsigned NumIndirectDests = Record[OpNum++]; |
5456 | SmallVector<BasicBlock *, 16> IndirectDests; |
5457 | for (unsigned i = 0, e = NumIndirectDests; i != e; ++i) |
5458 | IndirectDests.push_back(getBasicBlock(Record[OpNum++])); |
5459 | |
5460 | unsigned FTyID = InvalidTypeID; |
5461 | FunctionType *FTy = nullptr; |
5462 | if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { |
5463 | FTyID = Record[OpNum++]; |
5464 | FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); |
5465 | if (!FTy) |
5466 | return error("Explicit call type is not a function type"); |
5467 | } |
5468 | |
5469 | Value *Callee; |
5470 | unsigned CalleeTypeID; |
5471 | if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, |
5472 | CurBB)) |
5473 | return error("Invalid record"); |
5474 | |
5475 | PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); |
5476 | if (!OpTy) |
5477 | return error("Callee is not a pointer type"); |
5478 | if (!FTy) { |
5479 | FTyID = getContainedTypeID(CalleeTypeID); |
5480 | FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); |
5481 | if (!FTy) |
5482 | return error("Callee is not of pointer to function type"); |
5483 | } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy)) |
5484 | return error("Explicit call type does not match pointee type of " |
5485 | "callee operand"); |
5486 | if (Record.size() < FTy->getNumParams() + OpNum) |
5487 | return error("Insufficient operands to call"); |
5488 | |
5489 | SmallVector<Value*, 16> Args; |
5490 | SmallVector<unsigned, 16> ArgTyIDs; |
5491 | // Read the fixed params. |
5492 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { |
5493 | Value *Arg; |
5494 | unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); |
5495 | if (FTy->getParamType(i)->isLabelTy()) |
5496 | Arg = getBasicBlock(Record[OpNum]); |
5497 | else |
5498 | Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i), |
5499 | ArgTyID, CurBB); |
5500 | if (!Arg) |
5501 | return error("Invalid record"); |
5502 | Args.push_back(Arg); |
5503 | ArgTyIDs.push_back(ArgTyID); |
5504 | } |
5505 | |
5506 | // Read type/value pairs for varargs params. |
5507 | if (!FTy->isVarArg()) { |
5508 | if (OpNum != Record.size()) |
5509 | return error("Invalid record"); |
5510 | } else { |
5511 | while (OpNum != Record.size()) { |
5512 | Value *Op; |
5513 | unsigned OpTypeID; |
5514 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) |
5515 | return error("Invalid record"); |
5516 | Args.push_back(Op); |
5517 | ArgTyIDs.push_back(OpTypeID); |
5518 | } |
5519 | } |
5520 | |
5521 | // Upgrade the bundles if needed. |
5522 | if (!OperandBundles.empty()) |
5523 | UpgradeOperandBundles(OperandBundles); |
5524 | |
5525 | if (auto *IA = dyn_cast<InlineAsm>(Callee)) { |
5526 | InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints(); |
5527 | auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) { |
5528 | return CI.Type == InlineAsm::isLabel; |
5529 | }; |
5530 | if (none_of(ConstraintInfo, IsLabelConstraint)) { |
5531 | // Upgrade explicit blockaddress arguments to label constraints. |
5532 | // Verify that the last arguments are blockaddress arguments that |
5533 | // match the indirect destinations. Clang always generates callbr |
5534 | // in this form. We could support reordering with more effort. |
5535 | unsigned FirstBlockArg = Args.size() - IndirectDests.size(); |
5536 | for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) { |
5537 | unsigned LabelNo = ArgNo - FirstBlockArg; |
5538 | auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]); |
5539 | if (!BA || BA->getFunction() != F || |
5540 | LabelNo > IndirectDests.size() || |
5541 | BA->getBasicBlock() != IndirectDests[LabelNo]) |
5542 | return error("callbr argument does not match indirect dest"); |
5543 | } |
5544 | |
5545 | // Remove blockaddress arguments. |
5546 | Args.erase(Args.begin() + FirstBlockArg, Args.end()); |
5547 | ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end()); |
5548 | |
5549 | // Recreate the function type with less arguments. |
5550 | SmallVector<Type *> ArgTys; |
5551 | for (Value *Arg : Args) |
5552 | ArgTys.push_back(Arg->getType()); |
5553 | FTy = |
5554 | FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg()); |
5555 | |
5556 | // Update constraint string to use label constraints. |
5557 | std::string Constraints = IA->getConstraintString(); |
5558 | unsigned ArgNo = 0; |
5559 | size_t Pos = 0; |
5560 | for (const auto &CI : ConstraintInfo) { |
5561 | if (CI.hasArg()) { |
5562 | if (ArgNo >= FirstBlockArg) |
5563 | Constraints.insert(Pos, "!"); |
5564 | ++ArgNo; |
5565 | } |
5566 | |
5567 | // Go to next constraint in string. |
5568 | Pos = Constraints.find(',', Pos); |
5569 | if (Pos == std::string::npos) |
5570 | break; |
5571 | ++Pos; |
5572 | } |
5573 | |
5574 | Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints, |
5575 | IA->hasSideEffects(), IA->isAlignStack(), |
5576 | IA->getDialect(), IA->canThrow()); |
5577 | } |
5578 | } |
5579 | |
5580 | I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args, |
5581 | OperandBundles); |
5582 | ResTypeID = getContainedTypeID(FTyID); |
5583 | OperandBundles.clear(); |
5584 | InstructionList.push_back(I); |
5585 | cast<CallBrInst>(I)->setCallingConv( |
5586 | static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); |
5587 | cast<CallBrInst>(I)->setAttributes(PAL); |
5588 | if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { |
5589 | I->deleteValue(); |
5590 | return Err; |
5591 | } |
5592 | break; |
5593 | } |
5594 | case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE |
5595 | I = new UnreachableInst(Context); |
5596 | InstructionList.push_back(I); |
5597 | break; |
5598 | case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] |
5599 | if (Record.empty()) |
5600 | return error("Invalid phi record"); |
5601 | // The first record specifies the type. |
5602 | unsigned TyID = Record[0]; |
5603 | Type *Ty = getTypeByID(TyID); |
5604 | if (!Ty) |
5605 | return error("Invalid phi record"); |
5606 | |
5607 | // Phi arguments are pairs of records of [value, basic block]. |
5608 | // There is an optional final record for fast-math-flags if this phi has a |
5609 | // floating-point type. |
5610 | size_t NumArgs = (Record.size() - 1) / 2; |
5611 | PHINode *PN = PHINode::Create(Ty, NumArgs); |
5612 | if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) { |
5613 | PN->deleteValue(); |
5614 | return error("Invalid phi record"); |
5615 | } |
5616 | InstructionList.push_back(PN); |
5617 | |
5618 | SmallDenseMap<BasicBlock *, Value *> Args; |
5619 | for (unsigned i = 0; i != NumArgs; i++) { |
5620 | BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]); |
5621 | if (!BB) { |
5622 | PN->deleteValue(); |
5623 | return error("Invalid phi BB"); |
5624 | } |
5625 | |
5626 | // Phi nodes may contain the same predecessor multiple times, in which |
5627 | // case the incoming value must be identical. Directly reuse the already |
5628 | // seen value here, to avoid expanding a constant expression multiple |
5629 | // times. |
5630 | auto It = Args.find(BB); |
5631 | if (It != Args.end()) { |
5632 | PN->addIncoming(It->second, BB); |
5633 | continue; |
5634 | } |
5635 | |
5636 | // If there already is a block for this edge (from a different phi), |
5637 | // use it. |
5638 | BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB}); |
5639 | if (!EdgeBB) { |
5640 | // Otherwise, use a temporary block (that we will discard if it |
5641 | // turns out to be unnecessary). |
5642 | if (!PhiConstExprBB) |
5643 | PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F); |
5644 | EdgeBB = PhiConstExprBB; |
5645 | } |
5646 | |
5647 | // With the new function encoding, it is possible that operands have |
5648 | // negative IDs (for forward references). Use a signed VBR |
5649 | // representation to keep the encoding small. |
5650 | Value *V; |
5651 | if (UseRelativeIDs) |
5652 | V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB); |
5653 | else |
5654 | V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB); |
5655 | if (!V) { |
5656 | PN->deleteValue(); |
5657 | PhiConstExprBB->eraseFromParent(); |
5658 | return error("Invalid phi record"); |
5659 | } |
5660 | |
5661 | if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) { |
5662 | ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB}); |
5663 | PhiConstExprBB = nullptr; |
5664 | } |
5665 | PN->addIncoming(V, BB); |
5666 | Args.insert({BB, V}); |
5667 | } |
5668 | I = PN; |
5669 | ResTypeID = TyID; |
5670 | |
5671 | // If there are an even number of records, the final record must be FMF. |
5672 | if (Record.size() % 2 == 0) { |
5673 | assert(isa<FPMathOperator>(I) && "Unexpected phi type")(static_cast <bool> (isa<FPMathOperator>(I) && "Unexpected phi type") ? void (0) : __assert_fail ("isa<FPMathOperator>(I) && \"Unexpected phi type\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5673, __extension__ __PRETTY_FUNCTION__)); |
5674 | FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]); |
5675 | if (FMF.any()) |
5676 | I->setFastMathFlags(FMF); |
5677 | } |
5678 | |
5679 | break; |
5680 | } |
5681 | |
5682 | case bitc::FUNC_CODE_INST_LANDINGPAD: |
5683 | case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { |
5684 | // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] |
5685 | unsigned Idx = 0; |
5686 | if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { |
5687 | if (Record.size() < 3) |
5688 | return error("Invalid record"); |
5689 | } else { |
5690 | assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD)(static_cast <bool> (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD ) ? void (0) : __assert_fail ("BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5690, __extension__ __PRETTY_FUNCTION__)); |
5691 | if (Record.size() < 4) |
5692 | return error("Invalid record"); |
5693 | } |
5694 | ResTypeID = Record[Idx++]; |
5695 | Type *Ty = getTypeByID(ResTypeID); |
5696 | if (!Ty) |
5697 | return error("Invalid record"); |
5698 | if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { |
5699 | Value *PersFn = nullptr; |
5700 | unsigned PersFnTypeID; |
5701 | if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID, |
5702 | nullptr)) |
5703 | return error("Invalid record"); |
5704 | |
5705 | if (!F->hasPersonalityFn()) |
5706 | F->setPersonalityFn(cast<Constant>(PersFn)); |
5707 | else if (F->getPersonalityFn() != cast<Constant>(PersFn)) |
5708 | return error("Personality function mismatch"); |
5709 | } |
5710 | |
5711 | bool IsCleanup = !!Record[Idx++]; |
5712 | unsigned NumClauses = Record[Idx++]; |
5713 | LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); |
5714 | LP->setCleanup(IsCleanup); |
5715 | for (unsigned J = 0; J != NumClauses; ++J) { |
5716 | LandingPadInst::ClauseType CT = |
5717 | LandingPadInst::ClauseType(Record[Idx++]); (void)CT; |
5718 | Value *Val; |
5719 | unsigned ValTypeID; |
5720 | |
5721 | if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, |
5722 | nullptr)) { |
5723 | delete LP; |
5724 | return error("Invalid record"); |
5725 | } |
5726 | |
5727 | assert((CT != LandingPadInst::Catch ||(static_cast <bool> ((CT != LandingPadInst::Catch || !isa <ArrayType>(Val->getType())) && "Catch clause has a invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5729, __extension__ __PRETTY_FUNCTION__)) |
5728 | !isa<ArrayType>(Val->getType())) &&(static_cast <bool> ((CT != LandingPadInst::Catch || !isa <ArrayType>(Val->getType())) && "Catch clause has a invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5729, __extension__ __PRETTY_FUNCTION__)) |
5729 | "Catch clause has a invalid type!")(static_cast <bool> ((CT != LandingPadInst::Catch || !isa <ArrayType>(Val->getType())) && "Catch clause has a invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Catch || !isa<ArrayType>(Val->getType())) && \"Catch clause has a invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5729, __extension__ __PRETTY_FUNCTION__)); |
5730 | assert((CT != LandingPadInst::Filter ||(static_cast <bool> ((CT != LandingPadInst::Filter || isa <ArrayType>(Val->getType())) && "Filter clause has invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5732, __extension__ __PRETTY_FUNCTION__)) |
5731 | isa<ArrayType>(Val->getType())) &&(static_cast <bool> ((CT != LandingPadInst::Filter || isa <ArrayType>(Val->getType())) && "Filter clause has invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5732, __extension__ __PRETTY_FUNCTION__)) |
5732 | "Filter clause has invalid type!")(static_cast <bool> ((CT != LandingPadInst::Filter || isa <ArrayType>(Val->getType())) && "Filter clause has invalid type!" ) ? void (0) : __assert_fail ("(CT != LandingPadInst::Filter || isa<ArrayType>(Val->getType())) && \"Filter clause has invalid type!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 5732, __extension__ __PRETTY_FUNCTION__)); |
5733 | LP->addClause(cast<Constant>(Val)); |
5734 | } |
5735 | |
5736 | I = LP; |
5737 | InstructionList.push_back(I); |
5738 | break; |
5739 | } |
5740 | |
5741 | case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] |
5742 | if (Record.size() != 4 && Record.size() != 5) |
5743 | return error("Invalid record"); |
5744 | using APV = AllocaPackedValues; |
5745 | const uint64_t Rec = Record[3]; |
5746 | const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec); |
5747 | const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec); |
5748 | unsigned TyID = Record[0]; |
5749 | Type *Ty = getTypeByID(TyID); |
5750 | if (!Bitfield::get<APV::ExplicitType>(Rec)) { |
5751 | TyID = getContainedTypeID(TyID); |
5752 | Ty = getTypeByID(TyID); |
5753 | if (!Ty) |
5754 | return error("Missing element type for old-style alloca"); |
5755 | } |
5756 | unsigned OpTyID = Record[1]; |
5757 | Type *OpTy = getTypeByID(OpTyID); |
5758 | Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB); |
5759 | MaybeAlign Align; |
5760 | uint64_t AlignExp = |
5761 | Bitfield::get<APV::AlignLower>(Rec) | |
5762 | (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits); |
5763 | if (Error Err = parseAlignmentValue(AlignExp, Align)) { |
5764 | return Err; |
5765 | } |
5766 | if (!Ty || !Size) |
5767 | return error("Invalid record"); |
5768 | |
5769 | const DataLayout &DL = TheModule->getDataLayout(); |
5770 | unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace(); |
5771 | |
5772 | SmallPtrSet<Type *, 4> Visited; |
5773 | if (!Align && !Ty->isSized(&Visited)) |
5774 | return error("alloca of unsized type"); |
5775 | if (!Align) |
5776 | Align = DL.getPrefTypeAlign(Ty); |
5777 | |
5778 | AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align); |
5779 | AI->setUsedWithInAlloca(InAlloca); |
5780 | AI->setSwiftError(SwiftError); |
5781 | I = AI; |
5782 | ResTypeID = getVirtualTypeID(AI->getType(), TyID); |
5783 | InstructionList.push_back(I); |
5784 | break; |
5785 | } |
5786 | case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] |
5787 | unsigned OpNum = 0; |
5788 | Value *Op; |
5789 | unsigned OpTypeID; |
5790 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || |
5791 | (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) |
5792 | return error("Invalid record"); |
5793 | |
5794 | if (!isa<PointerType>(Op->getType())) |
5795 | return error("Load operand is not a pointer type"); |
5796 | |
5797 | Type *Ty = nullptr; |
5798 | if (OpNum + 3 == Record.size()) { |
5799 | ResTypeID = Record[OpNum++]; |
5800 | Ty = getTypeByID(ResTypeID); |
5801 | } else { |
5802 | ResTypeID = getContainedTypeID(OpTypeID); |
5803 | Ty = getTypeByID(ResTypeID); |
5804 | if (!Ty) |
5805 | return error("Missing element type for old-style load"); |
5806 | } |
5807 | |
5808 | if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) |
5809 | return Err; |
5810 | |
5811 | MaybeAlign Align; |
5812 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) |
5813 | return Err; |
5814 | SmallPtrSet<Type *, 4> Visited; |
5815 | if (!Align && !Ty->isSized(&Visited)) |
5816 | return error("load of unsized type"); |
5817 | if (!Align) |
5818 | Align = TheModule->getDataLayout().getABITypeAlign(Ty); |
5819 | I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align); |
5820 | InstructionList.push_back(I); |
5821 | break; |
5822 | } |
5823 | case bitc::FUNC_CODE_INST_LOADATOMIC: { |
5824 | // LOADATOMIC: [opty, op, align, vol, ordering, ssid] |
5825 | unsigned OpNum = 0; |
5826 | Value *Op; |
5827 | unsigned OpTypeID; |
5828 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || |
5829 | (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) |
5830 | return error("Invalid record"); |
5831 | |
5832 | if (!isa<PointerType>(Op->getType())) |
5833 | return error("Load operand is not a pointer type"); |
5834 | |
5835 | Type *Ty = nullptr; |
5836 | if (OpNum + 5 == Record.size()) { |
5837 | ResTypeID = Record[OpNum++]; |
5838 | Ty = getTypeByID(ResTypeID); |
5839 | } else { |
5840 | ResTypeID = getContainedTypeID(OpTypeID); |
5841 | Ty = getTypeByID(ResTypeID); |
5842 | if (!Ty) |
5843 | return error("Missing element type for old style atomic load"); |
5844 | } |
5845 | |
5846 | if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) |
5847 | return Err; |
5848 | |
5849 | AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); |
5850 | if (Ordering == AtomicOrdering::NotAtomic || |
5851 | Ordering == AtomicOrdering::Release || |
5852 | Ordering == AtomicOrdering::AcquireRelease) |
5853 | return error("Invalid record"); |
5854 | if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) |
5855 | return error("Invalid record"); |
5856 | SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); |
5857 | |
5858 | MaybeAlign Align; |
5859 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) |
5860 | return Err; |
5861 | if (!Align) |
5862 | return error("Alignment missing from atomic load"); |
5863 | I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID); |
5864 | InstructionList.push_back(I); |
5865 | break; |
5866 | } |
5867 | case bitc::FUNC_CODE_INST_STORE: |
5868 | case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] |
5869 | unsigned OpNum = 0; |
5870 | Value *Val, *Ptr; |
5871 | unsigned PtrTypeID, ValTypeID; |
5872 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) |
5873 | return error("Invalid record"); |
5874 | |
5875 | if (BitCode == bitc::FUNC_CODE_INST_STORE) { |
5876 | if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) |
5877 | return error("Invalid record"); |
5878 | } else { |
5879 | ValTypeID = getContainedTypeID(PtrTypeID); |
5880 | if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID), |
5881 | ValTypeID, Val, CurBB)) |
5882 | return error("Invalid record"); |
5883 | } |
5884 | |
5885 | if (OpNum + 2 != Record.size()) |
5886 | return error("Invalid record"); |
5887 | |
5888 | if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) |
5889 | return Err; |
5890 | MaybeAlign Align; |
5891 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) |
5892 | return Err; |
5893 | SmallPtrSet<Type *, 4> Visited; |
5894 | if (!Align && !Val->getType()->isSized(&Visited)) |
5895 | return error("store of unsized type"); |
5896 | if (!Align) |
5897 | Align = TheModule->getDataLayout().getABITypeAlign(Val->getType()); |
5898 | I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align); |
5899 | InstructionList.push_back(I); |
5900 | break; |
5901 | } |
5902 | case bitc::FUNC_CODE_INST_STOREATOMIC: |
5903 | case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { |
5904 | // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] |
5905 | unsigned OpNum = 0; |
5906 | Value *Val, *Ptr; |
5907 | unsigned PtrTypeID, ValTypeID; |
5908 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) || |
5909 | !isa<PointerType>(Ptr->getType())) |
5910 | return error("Invalid record"); |
5911 | if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) { |
5912 | if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) |
5913 | return error("Invalid record"); |
5914 | } else { |
5915 | ValTypeID = getContainedTypeID(PtrTypeID); |
5916 | if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID), |
5917 | ValTypeID, Val, CurBB)) |
5918 | return error("Invalid record"); |
5919 | } |
5920 | |
5921 | if (OpNum + 4 != Record.size()) |
5922 | return error("Invalid record"); |
5923 | |
5924 | if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) |
5925 | return Err; |
5926 | AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); |
5927 | if (Ordering == AtomicOrdering::NotAtomic || |
5928 | Ordering == AtomicOrdering::Acquire || |
5929 | Ordering == AtomicOrdering::AcquireRelease) |
5930 | return error("Invalid record"); |
5931 | SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); |
5932 | if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) |
5933 | return error("Invalid record"); |
5934 | |
5935 | MaybeAlign Align; |
5936 | if (Error Err = parseAlignmentValue(Record[OpNum], Align)) |
5937 | return Err; |
5938 | if (!Align) |
5939 | return error("Alignment missing from atomic store"); |
5940 | I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID); |
5941 | InstructionList.push_back(I); |
5942 | break; |
5943 | } |
5944 | case bitc::FUNC_CODE_INST_CMPXCHG_OLD: { |
5945 | // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope, |
5946 | // failure_ordering?, weak?] |
5947 | const size_t NumRecords = Record.size(); |
5948 | unsigned OpNum = 0; |
5949 | Value *Ptr = nullptr; |
5950 | unsigned PtrTypeID; |
5951 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) |
5952 | return error("Invalid record"); |
5953 | |
5954 | if (!isa<PointerType>(Ptr->getType())) |
5955 | return error("Cmpxchg operand is not a pointer type"); |
5956 | |
5957 | Value *Cmp = nullptr; |
5958 | unsigned CmpTypeID = getContainedTypeID(PtrTypeID); |
5959 | if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID), |
5960 | CmpTypeID, Cmp, CurBB)) |
5961 | return error("Invalid record"); |
5962 | |
5963 | Value *New = nullptr; |
5964 | if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, |
5965 | New, CurBB) || |
5966 | NumRecords < OpNum + 3 || NumRecords > OpNum + 5) |
5967 | return error("Invalid record"); |
5968 | |
5969 | const AtomicOrdering SuccessOrdering = |
5970 | getDecodedOrdering(Record[OpNum + 1]); |
5971 | if (SuccessOrdering == AtomicOrdering::NotAtomic || |
5972 | SuccessOrdering == AtomicOrdering::Unordered) |
5973 | return error("Invalid record"); |
5974 | |
5975 | const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); |
5976 | |
5977 | if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) |
5978 | return Err; |
5979 | |
5980 | const AtomicOrdering FailureOrdering = |
5981 | NumRecords < 7 |
5982 | ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering) |
5983 | : getDecodedOrdering(Record[OpNum + 3]); |
5984 | |
5985 | if (FailureOrdering == AtomicOrdering::NotAtomic || |
5986 | FailureOrdering == AtomicOrdering::Unordered) |
5987 | return error("Invalid record"); |
5988 | |
5989 | const Align Alignment( |
5990 | TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); |
5991 | |
5992 | I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering, |
5993 | FailureOrdering, SSID); |
5994 | cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); |
5995 | |
5996 | if (NumRecords < 8) { |
5997 | // Before weak cmpxchgs existed, the instruction simply returned the |
5998 | // value loaded from memory, so bitcode files from that era will be |
5999 | // expecting the first component of a modern cmpxchg. |
6000 | CurBB->getInstList().push_back(I); |
6001 | I = ExtractValueInst::Create(I, 0); |
6002 | ResTypeID = CmpTypeID; |
6003 | } else { |
6004 | cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]); |
6005 | unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context)); |
6006 | ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID}); |
6007 | } |
6008 | |
6009 | InstructionList.push_back(I); |
6010 | break; |
6011 | } |
6012 | case bitc::FUNC_CODE_INST_CMPXCHG: { |
6013 | // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope, |
6014 | // failure_ordering, weak, align?] |
6015 | const size_t NumRecords = Record.size(); |
6016 | unsigned OpNum = 0; |
6017 | Value *Ptr = nullptr; |
6018 | unsigned PtrTypeID; |
6019 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) |
6020 | return error("Invalid record"); |
6021 | |
6022 | if (!isa<PointerType>(Ptr->getType())) |
6023 | return error("Cmpxchg operand is not a pointer type"); |
6024 | |
6025 | Value *Cmp = nullptr; |
6026 | unsigned CmpTypeID; |
6027 | if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB)) |
6028 | return error("Invalid record"); |
6029 | |
6030 | Value *Val = nullptr; |
6031 | if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val, |
6032 | CurBB)) |
6033 | return error("Invalid record"); |
6034 | |
6035 | if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6) |
6036 | return error("Invalid record"); |
6037 | |
6038 | const bool IsVol = Record[OpNum]; |
6039 | |
6040 | const AtomicOrdering SuccessOrdering = |
6041 | getDecodedOrdering(Record[OpNum + 1]); |
6042 | if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) |
6043 | return error("Invalid cmpxchg success ordering"); |
6044 | |
6045 | const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); |
6046 | |
6047 | if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) |
6048 | return Err; |
6049 | |
6050 | const AtomicOrdering FailureOrdering = |
6051 | getDecodedOrdering(Record[OpNum + 3]); |
6052 | if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) |
6053 | return error("Invalid cmpxchg failure ordering"); |
6054 | |
6055 | const bool IsWeak = Record[OpNum + 4]; |
6056 | |
6057 | MaybeAlign Alignment; |
6058 | |
6059 | if (NumRecords == (OpNum + 6)) { |
6060 | if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment)) |
6061 | return Err; |
6062 | } |
6063 | if (!Alignment) |
6064 | Alignment = |
6065 | Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); |
6066 | |
6067 | I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering, |
6068 | FailureOrdering, SSID); |
6069 | cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol); |
6070 | cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak); |
6071 | |
6072 | unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context)); |
6073 | ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID}); |
6074 | |
6075 | InstructionList.push_back(I); |
6076 | break; |
6077 | } |
6078 | case bitc::FUNC_CODE_INST_ATOMICRMW_OLD: |
6079 | case bitc::FUNC_CODE_INST_ATOMICRMW: { |
6080 | // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?] |
6081 | // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?] |
6082 | const size_t NumRecords = Record.size(); |
6083 | unsigned OpNum = 0; |
6084 | |
6085 | Value *Ptr = nullptr; |
6086 | unsigned PtrTypeID; |
6087 | if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) |
6088 | return error("Invalid record"); |
6089 | |
6090 | if (!isa<PointerType>(Ptr->getType())) |
6091 | return error("Invalid record"); |
6092 | |
6093 | Value *Val = nullptr; |
6094 | unsigned ValTypeID = InvalidTypeID; |
6095 | if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) { |
6096 | ValTypeID = getContainedTypeID(PtrTypeID); |
6097 | if (popValue(Record, OpNum, NextValueNo, |
6098 | getTypeByID(ValTypeID), ValTypeID, Val, CurBB)) |
6099 | return error("Invalid record"); |
6100 | } else { |
6101 | if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) |
6102 | return error("Invalid record"); |
6103 | } |
6104 | |
6105 | if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5))) |
6106 | return error("Invalid record"); |
6107 | |
6108 | const AtomicRMWInst::BinOp Operation = |
6109 | getDecodedRMWOperation(Record[OpNum]); |
6110 | if (Operation < AtomicRMWInst::FIRST_BINOP || |
6111 | Operation > AtomicRMWInst::LAST_BINOP) |
6112 | return error("Invalid record"); |
6113 | |
6114 | const bool IsVol = Record[OpNum + 1]; |
6115 | |
6116 | const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); |
6117 | if (Ordering == AtomicOrdering::NotAtomic || |
6118 | Ordering == AtomicOrdering::Unordered) |
6119 | return error("Invalid record"); |
6120 | |
6121 | const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); |
6122 | |
6123 | MaybeAlign Alignment; |
6124 | |
6125 | if (NumRecords == (OpNum + 5)) { |
6126 | if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment)) |
6127 | return Err; |
6128 | } |
6129 | |
6130 | if (!Alignment) |
6131 | Alignment = |
6132 | Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType())); |
6133 | |
6134 | I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID); |
6135 | ResTypeID = ValTypeID; |
6136 | cast<AtomicRMWInst>(I)->setVolatile(IsVol); |
6137 | |
6138 | InstructionList.push_back(I); |
6139 | break; |
6140 | } |
6141 | case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] |
6142 | if (2 != Record.size()) |
6143 | return error("Invalid record"); |
6144 | AtomicOrdering Ordering = getDecodedOrdering(Record[0]); |
6145 | if (Ordering == AtomicOrdering::NotAtomic || |
6146 | Ordering == AtomicOrdering::Unordered || |
6147 | Ordering == AtomicOrdering::Monotonic) |
6148 | return error("Invalid record"); |
6149 | SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); |
6150 | I = new FenceInst(Context, Ordering, SSID); |
6151 | InstructionList.push_back(I); |
6152 | break; |
6153 | } |
6154 | case bitc::FUNC_CODE_INST_CALL: { |
6155 | // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] |
6156 | if (Record.size() < 3) |
6157 | return error("Invalid record"); |
6158 | |
6159 | unsigned OpNum = 0; |
6160 | AttributeList PAL = getAttributes(Record[OpNum++]); |
6161 | unsigned CCInfo = Record[OpNum++]; |
6162 | |
6163 | FastMathFlags FMF; |
6164 | if ((CCInfo >> bitc::CALL_FMF) & 1) { |
6165 | FMF = getDecodedFastMathFlags(Record[OpNum++]); |
6166 | if (!FMF.any()) |
6167 | return error("Fast math flags indicator set for call with no FMF"); |
6168 | } |
6169 | |
6170 | unsigned FTyID = InvalidTypeID; |
6171 | FunctionType *FTy = nullptr; |
6172 | if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { |
6173 | FTyID = Record[OpNum++]; |
6174 | FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); |
6175 | if (!FTy) |
6176 | return error("Explicit call type is not a function type"); |
6177 | } |
6178 | |
6179 | Value *Callee; |
6180 | unsigned CalleeTypeID; |
6181 | if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, |
6182 | CurBB)) |
6183 | return error("Invalid record"); |
6184 | |
6185 | PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); |
6186 | if (!OpTy) |
6187 | return error("Callee is not a pointer type"); |
6188 | if (!FTy) { |
6189 | FTyID = getContainedTypeID(CalleeTypeID); |
6190 | FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); |
6191 | if (!FTy) |
6192 | return error("Callee is not of pointer to function type"); |
6193 | } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy)) |
6194 | return error("Explicit call type does not match pointee type of " |
6195 | "callee operand"); |
6196 | if (Record.size() < FTy->getNumParams() + OpNum) |
6197 | return error("Insufficient operands to call"); |
6198 | |
6199 | SmallVector<Value*, 16> Args; |
6200 | SmallVector<unsigned, 16> ArgTyIDs; |
6201 | // Read the fixed params. |
6202 | for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { |
6203 | unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); |
6204 | if (FTy->getParamType(i)->isLabelTy()) |
6205 | Args.push_back(getBasicBlock(Record[OpNum])); |
6206 | else |
6207 | Args.push_back(getValue(Record, OpNum, NextValueNo, |
6208 | FTy->getParamType(i), ArgTyID, CurBB)); |
6209 | ArgTyIDs.push_back(ArgTyID); |
6210 | if (!Args.back()) |
6211 | return error("Invalid record"); |
6212 | } |
6213 | |
6214 | // Read type/value pairs for varargs params. |
6215 | if (!FTy->isVarArg()) { |
6216 | if (OpNum != Record.size()) |
6217 | return error("Invalid record"); |
6218 | } else { |
6219 | while (OpNum != Record.size()) { |
6220 | Value *Op; |
6221 | unsigned OpTypeID; |
6222 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) |
6223 | return error("Invalid record"); |
6224 | Args.push_back(Op); |
6225 | ArgTyIDs.push_back(OpTypeID); |
6226 | } |
6227 | } |
6228 | |
6229 | // Upgrade the bundles if needed. |
6230 | if (!OperandBundles.empty()) |
6231 | UpgradeOperandBundles(OperandBundles); |
6232 | |
6233 | I = CallInst::Create(FTy, Callee, Args, OperandBundles); |
6234 | ResTypeID = getContainedTypeID(FTyID); |
6235 | OperandBundles.clear(); |
6236 | InstructionList.push_back(I); |
6237 | cast<CallInst>(I)->setCallingConv( |
6238 | static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); |
6239 | CallInst::TailCallKind TCK = CallInst::TCK_None; |
6240 | if (CCInfo & 1 << bitc::CALL_TAIL) |
6241 | TCK = CallInst::TCK_Tail; |
6242 | if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) |
6243 | TCK = CallInst::TCK_MustTail; |
6244 | if (CCInfo & (1 << bitc::CALL_NOTAIL)) |
6245 | TCK = CallInst::TCK_NoTail; |
6246 | cast<CallInst>(I)->setTailCallKind(TCK); |
6247 | cast<CallInst>(I)->setAttributes(PAL); |
6248 | if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { |
6249 | I->deleteValue(); |
6250 | return Err; |
6251 | } |
6252 | if (FMF.any()) { |
6253 | if (!isa<FPMathOperator>(I)) |
6254 | return error("Fast-math-flags specified for call without " |
6255 | "floating-point scalar or vector return type"); |
6256 | I->setFastMathFlags(FMF); |
6257 | } |
6258 | break; |
6259 | } |
6260 | case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] |
6261 | if (Record.size() < 3) |
6262 | return error("Invalid record"); |
6263 | unsigned OpTyID = Record[0]; |
6264 | Type *OpTy = getTypeByID(OpTyID); |
6265 | Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); |
6266 | ResTypeID = Record[2]; |
6267 | Type *ResTy = getTypeByID(ResTypeID); |
6268 | if (!OpTy || !Op || !ResTy) |
6269 | return error("Invalid record"); |
6270 | I = new VAArgInst(Op, ResTy); |
6271 | InstructionList.push_back(I); |
6272 | break; |
6273 | } |
6274 | |
6275 | case bitc::FUNC_CODE_OPERAND_BUNDLE: { |
6276 | // A call or an invoke can be optionally prefixed with some variable |
6277 | // number of operand bundle blocks. These blocks are read into |
6278 | // OperandBundles and consumed at the next call or invoke instruction. |
6279 | |
6280 | if (Record.empty() || Record[0] >= BundleTags.size()) |
6281 | return error("Invalid record"); |
6282 | |
6283 | std::vector<Value *> Inputs; |
6284 | |
6285 | unsigned OpNum = 1; |
6286 | while (OpNum != Record.size()) { |
6287 | Value *Op; |
6288 | unsigned OpTypeID; |
6289 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) |
6290 | return error("Invalid record"); |
6291 | Inputs.push_back(Op); |
6292 | } |
6293 | |
6294 | OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); |
6295 | continue; |
6296 | } |
6297 | |
6298 | case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval] |
6299 | unsigned OpNum = 0; |
6300 | Value *Op = nullptr; |
6301 | unsigned OpTypeID; |
6302 | if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) |
6303 | return error("Invalid record"); |
6304 | if (OpNum != Record.size()) |
6305 | return error("Invalid record"); |
6306 | |
6307 | I = new FreezeInst(Op); |
6308 | ResTypeID = OpTypeID; |
6309 | InstructionList.push_back(I); |
6310 | break; |
6311 | } |
6312 | } |
6313 | |
6314 | // Add instruction to end of current BB. If there is no current BB, reject |
6315 | // this file. |
6316 | if (!CurBB) { |
6317 | I->deleteValue(); |
6318 | return error("Invalid instruction with no BB"); |
6319 | } |
6320 | if (!OperandBundles.empty()) { |
6321 | I->deleteValue(); |
6322 | return error("Operand bundles found with no consumer"); |
6323 | } |
6324 | CurBB->getInstList().push_back(I); |
6325 | |
6326 | // If this was a terminator instruction, move to the next block. |
6327 | if (I->isTerminator()) { |
6328 | ++CurBBNo; |
6329 | CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; |
6330 | } |
6331 | |
6332 | // Non-void values get registered in the value table for future use. |
6333 | if (!I->getType()->isVoidTy()) { |
6334 | assert(I->getType() == getTypeByID(ResTypeID) &&(static_cast <bool> (I->getType() == getTypeByID(ResTypeID ) && "Incorrect result type ID") ? void (0) : __assert_fail ("I->getType() == getTypeByID(ResTypeID) && \"Incorrect result type ID\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6335, __extension__ __PRETTY_FUNCTION__)) |
6335 | "Incorrect result type ID")(static_cast <bool> (I->getType() == getTypeByID(ResTypeID ) && "Incorrect result type ID") ? void (0) : __assert_fail ("I->getType() == getTypeByID(ResTypeID) && \"Incorrect result type ID\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6335, __extension__ __PRETTY_FUNCTION__)); |
6336 | if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID)) |
6337 | return Err; |
6338 | } |
6339 | } |
6340 | |
6341 | OutOfRecordLoop: |
6342 | |
6343 | if (!OperandBundles.empty()) |
6344 | return error("Operand bundles found with no consumer"); |
6345 | |
6346 | // Check the function list for unresolved values. |
6347 | if (Argument *A = dyn_cast<Argument>(ValueList.back())) { |
6348 | if (!A->getParent()) { |
6349 | // We found at least one unresolved value. Nuke them all to avoid leaks. |
6350 | for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ |
6351 | if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { |
6352 | A->replaceAllUsesWith(PoisonValue::get(A->getType())); |
6353 | delete A; |
6354 | } |
6355 | } |
6356 | return error("Never resolved value found in function"); |
6357 | } |
6358 | } |
6359 | |
6360 | // Unexpected unresolved metadata about to be dropped. |
6361 | if (MDLoader->hasFwdRefs()) |
6362 | return error("Invalid function metadata: outgoing forward refs"); |
6363 | |
6364 | if (PhiConstExprBB) |
6365 | PhiConstExprBB->eraseFromParent(); |
6366 | |
6367 | for (const auto &Pair : ConstExprEdgeBBs) { |
6368 | BasicBlock *From = Pair.first.first; |
6369 | BasicBlock *To = Pair.first.second; |
6370 | BasicBlock *EdgeBB = Pair.second; |
6371 | BranchInst::Create(To, EdgeBB); |
6372 | From->getTerminator()->replaceSuccessorWith(To, EdgeBB); |
6373 | To->replacePhiUsesWith(From, EdgeBB); |
6374 | EdgeBB->moveBefore(To); |
6375 | } |
6376 | |
6377 | // Trim the value list down to the size it was before we parsed this function. |
6378 | ValueList.shrinkTo(ModuleValueListSize); |
6379 | MDLoader->shrinkTo(ModuleMDLoaderSize); |
6380 | std::vector<BasicBlock*>().swap(FunctionBBs); |
6381 | return Error::success(); |
6382 | } |
6383 | |
6384 | /// Find the function body in the bitcode stream |
6385 | Error BitcodeReader::findFunctionInStream( |
6386 | Function *F, |
6387 | DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { |
6388 | while (DeferredFunctionInfoIterator->second == 0) { |
6389 | // This is the fallback handling for the old format bitcode that |
6390 | // didn't contain the function index in the VST, or when we have |
6391 | // an anonymous function which would not have a VST entry. |
6392 | // Assert that we have one of those two cases. |
6393 | assert(VSTOffset == 0 || !F->hasName())(static_cast <bool> (VSTOffset == 0 || !F->hasName() ) ? void (0) : __assert_fail ("VSTOffset == 0 || !F->hasName()" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6393, __extension__ __PRETTY_FUNCTION__)); |
6394 | // Parse the next body in the stream and set its position in the |
6395 | // DeferredFunctionInfo map. |
6396 | if (Error Err = rememberAndSkipFunctionBodies()) |
6397 | return Err; |
6398 | } |
6399 | return Error::success(); |
6400 | } |
6401 | |
6402 | SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { |
6403 | if (Val == SyncScope::SingleThread || Val == SyncScope::System) |
6404 | return SyncScope::ID(Val); |
6405 | if (Val >= SSIDs.size()) |
6406 | return SyncScope::System; // Map unknown synchronization scopes to system. |
6407 | return SSIDs[Val]; |
6408 | } |
6409 | |
6410 | //===----------------------------------------------------------------------===// |
6411 | // GVMaterializer implementation |
6412 | //===----------------------------------------------------------------------===// |
6413 | |
6414 | Error BitcodeReader::materialize(GlobalValue *GV) { |
6415 | Function *F = dyn_cast<Function>(GV); |
6416 | // If it's not a function or is already material, ignore the request. |
6417 | if (!F || !F->isMaterializable()) |
6418 | return Error::success(); |
6419 | |
6420 | DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); |
6421 | assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!")(static_cast <bool> (DFII != DeferredFunctionInfo.end() && "Deferred function not found!") ? void (0) : __assert_fail ("DFII != DeferredFunctionInfo.end() && \"Deferred function not found!\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6421, __extension__ __PRETTY_FUNCTION__)); |
6422 | // If its position is recorded as 0, its body is somewhere in the stream |
6423 | // but we haven't seen it yet. |
6424 | if (DFII->second == 0) |
6425 | if (Error Err = findFunctionInStream(F, DFII)) |
6426 | return Err; |
6427 | |
6428 | // Materialize metadata before parsing any function bodies. |
6429 | if (Error Err = materializeMetadata()) |
6430 | return Err; |
6431 | |
6432 | // Move the bit stream to the saved position of the deferred function body. |
6433 | if (Error JumpFailed = Stream.JumpToBit(DFII->second)) |
6434 | return JumpFailed; |
6435 | if (Error Err = parseFunctionBody(F)) |
6436 | return Err; |
6437 | F->setIsMaterializable(false); |
6438 | |
6439 | if (StripDebugInfo) |
6440 | stripDebugInfo(*F); |
6441 | |
6442 | // Upgrade any old intrinsic calls in the function. |
6443 | for (auto &I : UpgradedIntrinsics) { |
6444 | for (User *U : llvm::make_early_inc_range(I.first->materialized_users())) |
6445 | if (CallInst *CI = dyn_cast<CallInst>(U)) |
6446 | UpgradeIntrinsicCall(CI, I.second); |
6447 | } |
6448 | |
6449 | // Update calls to the remangled intrinsics |
6450 | for (auto &I : RemangledIntrinsics) |
6451 | for (User *U : llvm::make_early_inc_range(I.first->materialized_users())) |
6452 | // Don't expect any other users than call sites |
6453 | cast<CallBase>(U)->setCalledFunction(I.second); |
6454 | |
6455 | // Finish fn->subprogram upgrade for materialized functions. |
6456 | if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) |
6457 | F->setSubprogram(SP); |
6458 | |
6459 | // Check if the TBAA Metadata are valid, otherwise we will need to strip them. |
6460 | if (!MDLoader->isStrippingTBAA()) { |
6461 | for (auto &I : instructions(F)) { |
6462 | MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); |
6463 | if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) |
6464 | continue; |
6465 | MDLoader->setStripTBAA(true); |
6466 | stripTBAA(F->getParent()); |
6467 | } |
6468 | } |
6469 | |
6470 | for (auto &I : instructions(F)) { |
6471 | // "Upgrade" older incorrect branch weights by dropping them. |
6472 | if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) { |
6473 | if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) { |
6474 | MDString *MDS = cast<MDString>(MD->getOperand(0)); |
6475 | StringRef ProfName = MDS->getString(); |
6476 | // Check consistency of !prof branch_weights metadata. |
6477 | if (!ProfName.equals("branch_weights")) |
6478 | continue; |
6479 | unsigned ExpectedNumOperands = 0; |
6480 | if (BranchInst *BI = dyn_cast<BranchInst>(&I)) |
6481 | ExpectedNumOperands = BI->getNumSuccessors(); |
6482 | else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) |
6483 | ExpectedNumOperands = SI->getNumSuccessors(); |
6484 | else if (isa<CallInst>(&I)) |
6485 | ExpectedNumOperands = 1; |
6486 | else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) |
6487 | ExpectedNumOperands = IBI->getNumDestinations(); |
6488 | else if (isa<SelectInst>(&I)) |
6489 | ExpectedNumOperands = 2; |
6490 | else |
6491 | continue; // ignore and continue. |
6492 | |
6493 | // If branch weight doesn't match, just strip branch weight. |
6494 | if (MD->getNumOperands() != 1 + ExpectedNumOperands) |
6495 | I.setMetadata(LLVMContext::MD_prof, nullptr); |
6496 | } |
6497 | } |
6498 | |
6499 | // Remove incompatible attributes on function calls. |
6500 | if (auto *CI = dyn_cast<CallBase>(&I)) { |
6501 | CI->removeRetAttrs(AttributeFuncs::typeIncompatible( |
6502 | CI->getFunctionType()->getReturnType())); |
6503 | |
6504 | for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo) |
6505 | CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible( |
6506 | CI->getArgOperand(ArgNo)->getType())); |
6507 | } |
6508 | } |
6509 | |
6510 | // Look for functions that rely on old function attribute behavior. |
6511 | UpgradeFunctionAttributes(*F); |
6512 | |
6513 | // Bring in any functions that this function forward-referenced via |
6514 | // blockaddresses. |
6515 | return materializeForwardReferencedFunctions(); |
6516 | } |
6517 | |
6518 | Error BitcodeReader::materializeModule() { |
6519 | if (Error Err = materializeMetadata()) |
6520 | return Err; |
6521 | |
6522 | // Promise to materialize all forward references. |
6523 | WillMaterializeAllForwardRefs = true; |
6524 | |
6525 | // Iterate over the module, deserializing any functions that are still on |
6526 | // disk. |
6527 | for (Function &F : *TheModule) { |
6528 | if (Error Err = materialize(&F)) |
6529 | return Err; |
6530 | } |
6531 | // At this point, if there are any function bodies, parse the rest of |
6532 | // the bits in the module past the last function block we have recorded |
6533 | // through either lazy scanning or the VST. |
6534 | if (LastFunctionBlockBit || NextUnreadBit) |
6535 | if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit |
6536 | ? LastFunctionBlockBit |
6537 | : NextUnreadBit)) |
6538 | return Err; |
6539 | |
6540 | // Check that all block address forward references got resolved (as we |
6541 | // promised above). |
6542 | if (!BasicBlockFwdRefs.empty()) |
6543 | return error("Never resolved function from blockaddress"); |
6544 | |
6545 | // Upgrade any intrinsic calls that slipped through (should not happen!) and |
6546 | // delete the old functions to clean up. We can't do this unless the entire |
6547 | // module is materialized because there could always be another function body |
6548 | // with calls to the old function. |
6549 | for (auto &I : UpgradedIntrinsics) { |
6550 | for (auto *U : I.first->users()) { |
6551 | if (CallInst *CI = dyn_cast<CallInst>(U)) |
6552 | UpgradeIntrinsicCall(CI, I.second); |
6553 | } |
6554 | if (!I.first->use_empty()) |
6555 | I.first->replaceAllUsesWith(I.second); |
6556 | I.first->eraseFromParent(); |
6557 | } |
6558 | UpgradedIntrinsics.clear(); |
6559 | // Do the same for remangled intrinsics |
6560 | for (auto &I : RemangledIntrinsics) { |
6561 | I.first->replaceAllUsesWith(I.second); |
6562 | I.first->eraseFromParent(); |
6563 | } |
6564 | RemangledIntrinsics.clear(); |
6565 | |
6566 | UpgradeDebugInfo(*TheModule); |
6567 | |
6568 | UpgradeModuleFlags(*TheModule); |
6569 | |
6570 | UpgradeARCRuntime(*TheModule); |
6571 | |
6572 | return Error::success(); |
6573 | } |
6574 | |
6575 | std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { |
6576 | return IdentifiedStructTypes; |
6577 | } |
6578 | |
6579 | ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( |
6580 | BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, |
6581 | StringRef ModulePath, unsigned ModuleId) |
6582 | : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), |
6583 | ModulePath(ModulePath), ModuleId(ModuleId) {} |
6584 | |
6585 | void ModuleSummaryIndexBitcodeReader::addThisModule() { |
6586 | TheIndex.addModule(ModulePath, ModuleId); |
6587 | } |
6588 | |
6589 | ModuleSummaryIndex::ModuleInfo * |
6590 | ModuleSummaryIndexBitcodeReader::getThisModule() { |
6591 | return TheIndex.getModule(ModulePath); |
6592 | } |
6593 | |
6594 | std::pair<ValueInfo, GlobalValue::GUID> |
6595 | ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { |
6596 | auto VGI = ValueIdToValueInfoMap[ValueId]; |
6597 | assert(VGI.first)(static_cast <bool> (VGI.first) ? void (0) : __assert_fail ("VGI.first", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6597 , __extension__ __PRETTY_FUNCTION__)); |
6598 | return VGI; |
6599 | } |
6600 | |
6601 | void ModuleSummaryIndexBitcodeReader::setValueGUID( |
6602 | uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, |
6603 | StringRef SourceFileName) { |
6604 | std::string GlobalId = |
6605 | GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); |
6606 | auto ValueGUID = GlobalValue::getGUID(GlobalId); |
6607 | auto OriginalNameID = ValueGUID; |
6608 | if (GlobalValue::isLocalLinkage(Linkage)) |
6609 | OriginalNameID = GlobalValue::getGUID(ValueName); |
6610 | if (PrintSummaryGUIDs) |
6611 | dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " |
6612 | << ValueName << "\n"; |
6613 | |
6614 | // UseStrtab is false for legacy summary formats and value names are |
6615 | // created on stack. In that case we save the name in a string saver in |
6616 | // the index so that the value name can be recorded. |
6617 | ValueIdToValueInfoMap[ValueID] = std::make_pair( |
6618 | TheIndex.getOrInsertValueInfo( |
6619 | ValueGUID, |
6620 | UseStrtab ? ValueName : TheIndex.saveString(ValueName)), |
6621 | OriginalNameID); |
6622 | } |
6623 | |
6624 | // Specialized value symbol table parser used when reading module index |
6625 | // blocks where we don't actually create global values. The parsed information |
6626 | // is saved in the bitcode reader for use when later parsing summaries. |
6627 | Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( |
6628 | uint64_t Offset, |
6629 | DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { |
6630 | // With a strtab the VST is not required to parse the summary. |
6631 | if (UseStrtab) |
6632 | return Error::success(); |
6633 | |
6634 | assert(Offset > 0 && "Expected non-zero VST offset")(static_cast <bool> (Offset > 0 && "Expected non-zero VST offset" ) ? void (0) : __assert_fail ("Offset > 0 && \"Expected non-zero VST offset\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6634, __extension__ __PRETTY_FUNCTION__)); |
6635 | Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); |
6636 | if (!MaybeCurrentBit) |
6637 | return MaybeCurrentBit.takeError(); |
6638 | uint64_t CurrentBit = MaybeCurrentBit.get(); |
6639 | |
6640 | if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) |
6641 | return Err; |
6642 | |
6643 | SmallVector<uint64_t, 64> Record; |
6644 | |
6645 | // Read all the records for this value table. |
6646 | SmallString<128> ValueName; |
6647 | |
6648 | while (true) { |
6649 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
6650 | if (!MaybeEntry) |
6651 | return MaybeEntry.takeError(); |
6652 | BitstreamEntry Entry = MaybeEntry.get(); |
6653 | |
6654 | switch (Entry.Kind) { |
6655 | case BitstreamEntry::SubBlock: // Handled for us already. |
6656 | case BitstreamEntry::Error: |
6657 | return error("Malformed block"); |
6658 | case BitstreamEntry::EndBlock: |
6659 | // Done parsing VST, jump back to wherever we came from. |
6660 | if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) |
6661 | return JumpFailed; |
6662 | return Error::success(); |
6663 | case BitstreamEntry::Record: |
6664 | // The interesting case. |
6665 | break; |
6666 | } |
6667 | |
6668 | // Read a record. |
6669 | Record.clear(); |
6670 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
6671 | if (!MaybeRecord) |
6672 | return MaybeRecord.takeError(); |
6673 | switch (MaybeRecord.get()) { |
6674 | default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). |
6675 | break; |
6676 | case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] |
6677 | if (convertToString(Record, 1, ValueName)) |
6678 | return error("Invalid record"); |
6679 | unsigned ValueID = Record[0]; |
6680 | assert(!SourceFileName.empty())(static_cast <bool> (!SourceFileName.empty()) ? void (0 ) : __assert_fail ("!SourceFileName.empty()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6680, __extension__ __PRETTY_FUNCTION__)); |
6681 | auto VLI = ValueIdToLinkageMap.find(ValueID); |
6682 | assert(VLI != ValueIdToLinkageMap.end() &&(static_cast <bool> (VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?") ? void (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6683, __extension__ __PRETTY_FUNCTION__)) |
6683 | "No linkage found for VST entry?")(static_cast <bool> (VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?") ? void (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6683, __extension__ __PRETTY_FUNCTION__)); |
6684 | auto Linkage = VLI->second; |
6685 | setValueGUID(ValueID, ValueName, Linkage, SourceFileName); |
6686 | ValueName.clear(); |
6687 | break; |
6688 | } |
6689 | case bitc::VST_CODE_FNENTRY: { |
6690 | // VST_CODE_FNENTRY: [valueid, offset, namechar x N] |
6691 | if (convertToString(Record, 2, ValueName)) |
6692 | return error("Invalid record"); |
6693 | unsigned ValueID = Record[0]; |
6694 | assert(!SourceFileName.empty())(static_cast <bool> (!SourceFileName.empty()) ? void (0 ) : __assert_fail ("!SourceFileName.empty()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6694, __extension__ __PRETTY_FUNCTION__)); |
6695 | auto VLI = ValueIdToLinkageMap.find(ValueID); |
6696 | assert(VLI != ValueIdToLinkageMap.end() &&(static_cast <bool> (VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?") ? void (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6697, __extension__ __PRETTY_FUNCTION__)) |
6697 | "No linkage found for VST entry?")(static_cast <bool> (VLI != ValueIdToLinkageMap.end() && "No linkage found for VST entry?") ? void (0) : __assert_fail ("VLI != ValueIdToLinkageMap.end() && \"No linkage found for VST entry?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6697, __extension__ __PRETTY_FUNCTION__)); |
6698 | auto Linkage = VLI->second; |
6699 | setValueGUID(ValueID, ValueName, Linkage, SourceFileName); |
6700 | ValueName.clear(); |
6701 | break; |
6702 | } |
6703 | case bitc::VST_CODE_COMBINED_ENTRY: { |
6704 | // VST_CODE_COMBINED_ENTRY: [valueid, refguid] |
6705 | unsigned ValueID = Record[0]; |
6706 | GlobalValue::GUID RefGUID = Record[1]; |
6707 | // The "original name", which is the second value of the pair will be |
6708 | // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. |
6709 | ValueIdToValueInfoMap[ValueID] = |
6710 | std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); |
6711 | break; |
6712 | } |
6713 | } |
6714 | } |
6715 | } |
6716 | |
6717 | // Parse just the blocks needed for building the index out of the module. |
6718 | // At the end of this routine the module Index is populated with a map |
6719 | // from global value id to GlobalValueSummary objects. |
6720 | Error ModuleSummaryIndexBitcodeReader::parseModule() { |
6721 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) |
6722 | return Err; |
6723 | |
6724 | SmallVector<uint64_t, 64> Record; |
6725 | DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; |
6726 | unsigned ValueId = 0; |
6727 | |
6728 | // Read the index for this module. |
6729 | while (true) { |
6730 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
6731 | if (!MaybeEntry) |
6732 | return MaybeEntry.takeError(); |
6733 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
6734 | |
6735 | switch (Entry.Kind) { |
6736 | case BitstreamEntry::Error: |
6737 | return error("Malformed block"); |
6738 | case BitstreamEntry::EndBlock: |
6739 | return Error::success(); |
6740 | |
6741 | case BitstreamEntry::SubBlock: |
6742 | switch (Entry.ID) { |
6743 | default: // Skip unknown content. |
6744 | if (Error Err = Stream.SkipBlock()) |
6745 | return Err; |
6746 | break; |
6747 | case bitc::BLOCKINFO_BLOCK_ID: |
6748 | // Need to parse these to get abbrev ids (e.g. for VST) |
6749 | if (Error Err = readBlockInfo()) |
6750 | return Err; |
6751 | break; |
6752 | case bitc::VALUE_SYMTAB_BLOCK_ID: |
6753 | // Should have been parsed earlier via VSTOffset, unless there |
6754 | // is no summary section. |
6755 | assert(((SeenValueSymbolTable && VSTOffset > 0) ||(static_cast <bool> (((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && "Expected early VST parse via VSTOffset record" ) ? void (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6757, __extension__ __PRETTY_FUNCTION__)) |
6756 | !SeenGlobalValSummary) &&(static_cast <bool> (((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && "Expected early VST parse via VSTOffset record" ) ? void (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6757, __extension__ __PRETTY_FUNCTION__)) |
6757 | "Expected early VST parse via VSTOffset record")(static_cast <bool> (((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && "Expected early VST parse via VSTOffset record" ) ? void (0) : __assert_fail ("((SeenValueSymbolTable && VSTOffset > 0) || !SeenGlobalValSummary) && \"Expected early VST parse via VSTOffset record\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6757, __extension__ __PRETTY_FUNCTION__)); |
6758 | if (Error Err = Stream.SkipBlock()) |
6759 | return Err; |
6760 | break; |
6761 | case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: |
6762 | case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: |
6763 | // Add the module if it is a per-module index (has a source file name). |
6764 | if (!SourceFileName.empty()) |
6765 | addThisModule(); |
6766 | assert(!SeenValueSymbolTable &&(static_cast <bool> (!SeenValueSymbolTable && "Already read VST when parsing summary block?" ) ? void (0) : __assert_fail ("!SeenValueSymbolTable && \"Already read VST when parsing summary block?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6767, __extension__ __PRETTY_FUNCTION__)) |
6767 | "Already read VST when parsing summary block?")(static_cast <bool> (!SeenValueSymbolTable && "Already read VST when parsing summary block?" ) ? void (0) : __assert_fail ("!SeenValueSymbolTable && \"Already read VST when parsing summary block?\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6767, __extension__ __PRETTY_FUNCTION__)); |
6768 | // We might not have a VST if there were no values in the |
6769 | // summary. An empty summary block generated when we are |
6770 | // performing ThinLTO compiles so we don't later invoke |
6771 | // the regular LTO process on them. |
6772 | if (VSTOffset > 0) { |
6773 | if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) |
6774 | return Err; |
6775 | SeenValueSymbolTable = true; |
6776 | } |
6777 | SeenGlobalValSummary = true; |
6778 | if (Error Err = parseEntireSummary(Entry.ID)) |
6779 | return Err; |
6780 | break; |
6781 | case bitc::MODULE_STRTAB_BLOCK_ID: |
6782 | if (Error Err = parseModuleStringTable()) |
6783 | return Err; |
6784 | break; |
6785 | } |
6786 | continue; |
6787 | |
6788 | case BitstreamEntry::Record: { |
6789 | Record.clear(); |
6790 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); |
6791 | if (!MaybeBitCode) |
6792 | return MaybeBitCode.takeError(); |
6793 | switch (MaybeBitCode.get()) { |
6794 | default: |
6795 | break; // Default behavior, ignore unknown content. |
6796 | case bitc::MODULE_CODE_VERSION: { |
6797 | if (Error Err = parseVersionRecord(Record).takeError()) |
6798 | return Err; |
6799 | break; |
6800 | } |
6801 | /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] |
6802 | case bitc::MODULE_CODE_SOURCE_FILENAME: { |
6803 | SmallString<128> ValueName; |
6804 | if (convertToString(Record, 0, ValueName)) |
6805 | return error("Invalid record"); |
6806 | SourceFileName = ValueName.c_str(); |
6807 | break; |
6808 | } |
6809 | /// MODULE_CODE_HASH: [5*i32] |
6810 | case bitc::MODULE_CODE_HASH: { |
6811 | if (Record.size() != 5) |
6812 | return error("Invalid hash length " + Twine(Record.size()).str()); |
6813 | auto &Hash = getThisModule()->second.second; |
6814 | int Pos = 0; |
6815 | for (auto &Val : Record) { |
6816 | assert(!(Val >> 32) && "Unexpected high bits set")(static_cast <bool> (!(Val >> 32) && "Unexpected high bits set" ) ? void (0) : __assert_fail ("!(Val >> 32) && \"Unexpected high bits set\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 6816, __extension__ __PRETTY_FUNCTION__)); |
6817 | Hash[Pos++] = Val; |
6818 | } |
6819 | break; |
6820 | } |
6821 | /// MODULE_CODE_VSTOFFSET: [offset] |
6822 | case bitc::MODULE_CODE_VSTOFFSET: |
6823 | if (Record.empty()) |
6824 | return error("Invalid record"); |
6825 | // Note that we subtract 1 here because the offset is relative to one |
6826 | // word before the start of the identification or module block, which |
6827 | // was historically always the start of the regular bitcode header. |
6828 | VSTOffset = Record[0] - 1; |
6829 | break; |
6830 | // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] |
6831 | // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] |
6832 | // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] |
6833 | // v2: [strtab offset, strtab size, v1] |
6834 | case bitc::MODULE_CODE_GLOBALVAR: |
6835 | case bitc::MODULE_CODE_FUNCTION: |
6836 | case bitc::MODULE_CODE_ALIAS: { |
6837 | StringRef Name; |
6838 | ArrayRef<uint64_t> GVRecord; |
6839 | std::tie(Name, GVRecord) = readNameFromStrtab(Record); |
6840 | if (GVRecord.size() <= 3) |
6841 | return error("Invalid record"); |
6842 | uint64_t RawLinkage = GVRecord[3]; |
6843 | GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); |
6844 | if (!UseStrtab) { |
6845 | ValueIdToLinkageMap[ValueId++] = Linkage; |
6846 | break; |
6847 | } |
6848 | |
6849 | setValueGUID(ValueId++, Name, Linkage, SourceFileName); |
6850 | break; |
6851 | } |
6852 | } |
6853 | } |
6854 | continue; |
6855 | } |
6856 | } |
6857 | } |
6858 | |
6859 | std::vector<ValueInfo> |
6860 | ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { |
6861 | std::vector<ValueInfo> Ret; |
6862 | Ret.reserve(Record.size()); |
6863 | for (uint64_t RefValueId : Record) |
6864 | Ret.push_back(getValueInfoFromValueId(RefValueId).first); |
6865 | return Ret; |
6866 | } |
6867 | |
6868 | std::vector<FunctionSummary::EdgeTy> |
6869 | ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, |
6870 | bool IsOldProfileFormat, |
6871 | bool HasProfile, bool HasRelBF) { |
6872 | std::vector<FunctionSummary::EdgeTy> Ret; |
6873 | Ret.reserve(Record.size()); |
6874 | for (unsigned I = 0, E = Record.size(); I != E; ++I) { |
6875 | CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; |
6876 | uint64_t RelBF = 0; |
6877 | ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; |
6878 | if (IsOldProfileFormat) { |
6879 | I += 1; // Skip old callsitecount field |
6880 | if (HasProfile) |
6881 | I += 1; // Skip old profilecount field |
6882 | } else if (HasProfile) |
6883 | Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); |
6884 | else if (HasRelBF) |
6885 | RelBF = Record[++I]; |
6886 | Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)}); |
6887 | } |
6888 | return Ret; |
6889 | } |
6890 | |
6891 | static void |
6892 | parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, |
6893 | WholeProgramDevirtResolution &Wpd) { |
6894 | uint64_t ArgNum = Record[Slot++]; |
6895 | WholeProgramDevirtResolution::ByArg &B = |
6896 | Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; |
6897 | Slot += ArgNum; |
6898 | |
6899 | B.TheKind = |
6900 | static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); |
6901 | B.Info = Record[Slot++]; |
6902 | B.Byte = Record[Slot++]; |
6903 | B.Bit = Record[Slot++]; |
6904 | } |
6905 | |
6906 | static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, |
6907 | StringRef Strtab, size_t &Slot, |
6908 | TypeIdSummary &TypeId) { |
6909 | uint64_t Id = Record[Slot++]; |
6910 | WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; |
6911 | |
6912 | Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); |
6913 | Wpd.SingleImplName = {Strtab.data() + Record[Slot], |
6914 | static_cast<size_t>(Record[Slot + 1])}; |
6915 | Slot += 2; |
6916 | |
6917 | uint64_t ResByArgNum = Record[Slot++]; |
6918 | for (uint64_t I = 0; I != ResByArgNum; ++I) |
6919 | parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); |
6920 | } |
6921 | |
6922 | static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, |
6923 | StringRef Strtab, |
6924 | ModuleSummaryIndex &TheIndex) { |
6925 | size_t Slot = 0; |
6926 | TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( |
6927 | {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); |
6928 | Slot += 2; |
6929 | |
6930 | TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); |
6931 | TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; |
6932 | TypeId.TTRes.AlignLog2 = Record[Slot++]; |
6933 | TypeId.TTRes.SizeM1 = Record[Slot++]; |
6934 | TypeId.TTRes.BitMask = Record[Slot++]; |
6935 | TypeId.TTRes.InlineBits = Record[Slot++]; |
6936 | |
6937 | while (Slot < Record.size()) |
6938 | parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); |
6939 | } |
6940 | |
6941 | std::vector<FunctionSummary::ParamAccess> |
6942 | ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) { |
6943 | auto ReadRange = [&]() { |
6944 | APInt Lower(FunctionSummary::ParamAccess::RangeWidth, |
6945 | BitcodeReader::decodeSignRotatedValue(Record.front())); |
6946 | Record = Record.drop_front(); |
6947 | APInt Upper(FunctionSummary::ParamAccess::RangeWidth, |
6948 | BitcodeReader::decodeSignRotatedValue(Record.front())); |
6949 | Record = Record.drop_front(); |
6950 | ConstantRange Range{Lower, Upper}; |
6951 | assert(!Range.isFullSet())(static_cast <bool> (!Range.isFullSet()) ? void (0) : __assert_fail ("!Range.isFullSet()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6951, __extension__ __PRETTY_FUNCTION__)); |
6952 | assert(!Range.isUpperSignWrapped())(static_cast <bool> (!Range.isUpperSignWrapped()) ? void (0) : __assert_fail ("!Range.isUpperSignWrapped()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 6952, __extension__ __PRETTY_FUNCTION__)); |
6953 | return Range; |
6954 | }; |
6955 | |
6956 | std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; |
6957 | while (!Record.empty()) { |
6958 | PendingParamAccesses.emplace_back(); |
6959 | FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back(); |
6960 | ParamAccess.ParamNo = Record.front(); |
6961 | Record = Record.drop_front(); |
6962 | ParamAccess.Use = ReadRange(); |
6963 | ParamAccess.Calls.resize(Record.front()); |
6964 | Record = Record.drop_front(); |
6965 | for (auto &Call : ParamAccess.Calls) { |
6966 | Call.ParamNo = Record.front(); |
6967 | Record = Record.drop_front(); |
6968 | Call.Callee = getValueInfoFromValueId(Record.front()).first; |
6969 | Record = Record.drop_front(); |
6970 | Call.Offsets = ReadRange(); |
6971 | } |
6972 | } |
6973 | return PendingParamAccesses; |
6974 | } |
6975 | |
6976 | void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo( |
6977 | ArrayRef<uint64_t> Record, size_t &Slot, |
6978 | TypeIdCompatibleVtableInfo &TypeId) { |
6979 | uint64_t Offset = Record[Slot++]; |
6980 | ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first; |
6981 | TypeId.push_back({Offset, Callee}); |
6982 | } |
6983 | |
6984 | void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord( |
6985 | ArrayRef<uint64_t> Record) { |
6986 | size_t Slot = 0; |
6987 | TypeIdCompatibleVtableInfo &TypeId = |
6988 | TheIndex.getOrInsertTypeIdCompatibleVtableSummary( |
6989 | {Strtab.data() + Record[Slot], |
6990 | static_cast<size_t>(Record[Slot + 1])}); |
6991 | Slot += 2; |
6992 | |
6993 | while (Slot < Record.size()) |
6994 | parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId); |
6995 | } |
6996 | |
6997 | static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt, |
6998 | unsigned WOCnt) { |
6999 | // Readonly and writeonly refs are in the end of the refs list. |
7000 | assert(ROCnt + WOCnt <= Refs.size())(static_cast <bool> (ROCnt + WOCnt <= Refs.size()) ? void (0) : __assert_fail ("ROCnt + WOCnt <= Refs.size()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 7000, __extension__ __PRETTY_FUNCTION__)); |
7001 | unsigned FirstWORef = Refs.size() - WOCnt; |
7002 | unsigned RefNo = FirstWORef - ROCnt; |
7003 | for (; RefNo < FirstWORef; ++RefNo) |
7004 | Refs[RefNo].setReadOnly(); |
7005 | for (; RefNo < Refs.size(); ++RefNo) |
7006 | Refs[RefNo].setWriteOnly(); |
7007 | } |
7008 | |
7009 | // Eagerly parse the entire summary block. This populates the GlobalValueSummary |
7010 | // objects in the index. |
7011 | Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { |
7012 | if (Error Err = Stream.EnterSubBlock(ID)) |
7013 | return Err; |
7014 | SmallVector<uint64_t, 64> Record; |
7015 | |
7016 | // Parse version |
7017 | { |
7018 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
7019 | if (!MaybeEntry) |
7020 | return MaybeEntry.takeError(); |
7021 | BitstreamEntry Entry = MaybeEntry.get(); |
7022 | |
7023 | if (Entry.Kind != BitstreamEntry::Record) |
7024 | return error("Invalid Summary Block: record for version expected"); |
7025 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
7026 | if (!MaybeRecord) |
7027 | return MaybeRecord.takeError(); |
7028 | if (MaybeRecord.get() != bitc::FS_VERSION) |
7029 | return error("Invalid Summary Block: version expected"); |
7030 | } |
7031 | const uint64_t Version = Record[0]; |
7032 | const bool IsOldProfileFormat = Version == 1; |
7033 | if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion) |
7034 | return error("Invalid summary version " + Twine(Version) + |
7035 | ". Version should be in the range [1-" + |
7036 | Twine(ModuleSummaryIndex::BitcodeSummaryVersion) + |
7037 | "]."); |
7038 | Record.clear(); |
7039 | |
7040 | // Keep around the last seen summary to be used when we see an optional |
7041 | // "OriginalName" attachement. |
7042 | GlobalValueSummary *LastSeenSummary = nullptr; |
7043 | GlobalValue::GUID LastSeenGUID = 0; |
7044 | |
7045 | // We can expect to see any number of type ID information records before |
7046 | // each function summary records; these variables store the information |
7047 | // collected so far so that it can be used to create the summary object. |
7048 | std::vector<GlobalValue::GUID> PendingTypeTests; |
7049 | std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, |
7050 | PendingTypeCheckedLoadVCalls; |
7051 | std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, |
7052 | PendingTypeCheckedLoadConstVCalls; |
7053 | std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; |
7054 | |
7055 | while (true) { |
7056 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
7057 | if (!MaybeEntry) |
7058 | return MaybeEntry.takeError(); |
7059 | BitstreamEntry Entry = MaybeEntry.get(); |
7060 | |
7061 | switch (Entry.Kind) { |
7062 | case BitstreamEntry::SubBlock: // Handled for us already. |
7063 | case BitstreamEntry::Error: |
7064 | return error("Malformed block"); |
7065 | case BitstreamEntry::EndBlock: |
7066 | return Error::success(); |
7067 | case BitstreamEntry::Record: |
7068 | // The interesting case. |
7069 | break; |
7070 | } |
7071 | |
7072 | // Read a record. The record format depends on whether this |
7073 | // is a per-module index or a combined index file. In the per-module |
7074 | // case the records contain the associated value's ID for correlation |
7075 | // with VST entries. In the combined index the correlation is done |
7076 | // via the bitcode offset of the summary records (which were saved |
7077 | // in the combined index VST entries). The records also contain |
7078 | // information used for ThinLTO renaming and importing. |
7079 | Record.clear(); |
7080 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); |
7081 | if (!MaybeBitCode) |
7082 | return MaybeBitCode.takeError(); |
7083 | switch (unsigned BitCode = MaybeBitCode.get()) { |
7084 | default: // Default behavior: ignore. |
7085 | break; |
7086 | case bitc::FS_FLAGS: { // [flags] |
7087 | TheIndex.setFlags(Record[0]); |
7088 | break; |
7089 | } |
7090 | case bitc::FS_VALUE_GUID: { // [valueid, refguid] |
7091 | uint64_t ValueID = Record[0]; |
7092 | GlobalValue::GUID RefGUID = Record[1]; |
7093 | ValueIdToValueInfoMap[ValueID] = |
7094 | std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); |
7095 | break; |
7096 | } |
7097 | // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, |
7098 | // numrefs x valueid, n x (valueid)] |
7099 | // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, |
7100 | // numrefs x valueid, |
7101 | // n x (valueid, hotness)] |
7102 | // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, |
7103 | // numrefs x valueid, |
7104 | // n x (valueid, relblockfreq)] |
7105 | case bitc::FS_PERMODULE: |
7106 | case bitc::FS_PERMODULE_RELBF: |
7107 | case bitc::FS_PERMODULE_PROFILE: { |
7108 | unsigned ValueID = Record[0]; |
7109 | uint64_t RawFlags = Record[1]; |
7110 | unsigned InstCount = Record[2]; |
7111 | uint64_t RawFunFlags = 0; |
7112 | unsigned NumRefs = Record[3]; |
7113 | unsigned NumRORefs = 0, NumWORefs = 0; |
7114 | int RefListStartIndex = 4; |
7115 | if (Version >= 4) { |
7116 | RawFunFlags = Record[3]; |
7117 | NumRefs = Record[4]; |
7118 | RefListStartIndex = 5; |
7119 | if (Version >= 5) { |
7120 | NumRORefs = Record[5]; |
7121 | RefListStartIndex = 6; |
7122 | if (Version >= 7) { |
7123 | NumWORefs = Record[6]; |
7124 | RefListStartIndex = 7; |
7125 | } |
7126 | } |
7127 | } |
7128 | |
7129 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
7130 | // The module path string ref set in the summary must be owned by the |
7131 | // index's module string table. Since we don't have a module path |
7132 | // string table section in the per-module index, we create a single |
7133 | // module path string table entry with an empty (0) ID to take |
7134 | // ownership. |
7135 | int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; |
7136 | assert(Record.size() >= RefListStartIndex + NumRefs &&(static_cast <bool> (Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 7137, __extension__ __PRETTY_FUNCTION__)) |
7137 | "Record size inconsistent with number of references")(static_cast <bool> (Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 7137, __extension__ __PRETTY_FUNCTION__)); |
7138 | std::vector<ValueInfo> Refs = makeRefList( |
7139 | ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); |
7140 | bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); |
7141 | bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); |
7142 | std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( |
7143 | ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), |
7144 | IsOldProfileFormat, HasProfile, HasRelBF); |
7145 | setSpecialRefs(Refs, NumRORefs, NumWORefs); |
7146 | auto FS = std::make_unique<FunctionSummary>( |
7147 | Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0, |
7148 | std::move(Refs), std::move(Calls), std::move(PendingTypeTests), |
7149 | std::move(PendingTypeTestAssumeVCalls), |
7150 | std::move(PendingTypeCheckedLoadVCalls), |
7151 | std::move(PendingTypeTestAssumeConstVCalls), |
7152 | std::move(PendingTypeCheckedLoadConstVCalls), |
7153 | std::move(PendingParamAccesses)); |
7154 | auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); |
7155 | FS->setModulePath(getThisModule()->first()); |
7156 | FS->setOriginalName(VIAndOriginalGUID.second); |
7157 | TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS)); |
7158 | break; |
7159 | } |
7160 | // FS_ALIAS: [valueid, flags, valueid] |
7161 | // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as |
7162 | // they expect all aliasee summaries to be available. |
7163 | case bitc::FS_ALIAS: { |
7164 | unsigned ValueID = Record[0]; |
7165 | uint64_t RawFlags = Record[1]; |
7166 | unsigned AliaseeID = Record[2]; |
7167 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
7168 | auto AS = std::make_unique<AliasSummary>(Flags); |
7169 | // The module path string ref set in the summary must be owned by the |
7170 | // index's module string table. Since we don't have a module path |
7171 | // string table section in the per-module index, we create a single |
7172 | // module path string table entry with an empty (0) ID to take |
7173 | // ownership. |
7174 | AS->setModulePath(getThisModule()->first()); |
7175 | |
7176 | auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first; |
7177 | auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath); |
7178 | if (!AliaseeInModule) |
7179 | return error("Alias expects aliasee summary to be parsed"); |
7180 | AS->setAliasee(AliaseeVI, AliaseeInModule); |
7181 | |
7182 | auto GUID = getValueInfoFromValueId(ValueID); |
7183 | AS->setOriginalName(GUID.second); |
7184 | TheIndex.addGlobalValueSummary(GUID.first, std::move(AS)); |
7185 | break; |
7186 | } |
7187 | // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid] |
7188 | case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { |
7189 | unsigned ValueID = Record[0]; |
7190 | uint64_t RawFlags = Record[1]; |
7191 | unsigned RefArrayStart = 2; |
7192 | GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, |
7193 | /* WriteOnly */ false, |
7194 | /* Constant */ false, |
7195 | GlobalObject::VCallVisibilityPublic); |
7196 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
7197 | if (Version >= 5) { |
7198 | GVF = getDecodedGVarFlags(Record[2]); |
7199 | RefArrayStart = 3; |
7200 | } |
7201 | std::vector<ValueInfo> Refs = |
7202 | makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); |
7203 | auto FS = |
7204 | std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); |
7205 | FS->setModulePath(getThisModule()->first()); |
7206 | auto GUID = getValueInfoFromValueId(ValueID); |
7207 | FS->setOriginalName(GUID.second); |
7208 | TheIndex.addGlobalValueSummary(GUID.first, std::move(FS)); |
7209 | break; |
7210 | } |
7211 | // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, |
7212 | // numrefs, numrefs x valueid, |
7213 | // n x (valueid, offset)] |
7214 | case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: { |
7215 | unsigned ValueID = Record[0]; |
7216 | uint64_t RawFlags = Record[1]; |
7217 | GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]); |
7218 | unsigned NumRefs = Record[3]; |
7219 | unsigned RefListStartIndex = 4; |
7220 | unsigned VTableListStartIndex = RefListStartIndex + NumRefs; |
7221 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
7222 | std::vector<ValueInfo> Refs = makeRefList( |
7223 | ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); |
7224 | VTableFuncList VTableFuncs; |
7225 | for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) { |
7226 | ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; |
7227 | uint64_t Offset = Record[++I]; |
7228 | VTableFuncs.push_back({Callee, Offset}); |
7229 | } |
7230 | auto VS = |
7231 | std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); |
7232 | VS->setModulePath(getThisModule()->first()); |
7233 | VS->setVTableFuncs(VTableFuncs); |
7234 | auto GUID = getValueInfoFromValueId(ValueID); |
7235 | VS->setOriginalName(GUID.second); |
7236 | TheIndex.addGlobalValueSummary(GUID.first, std::move(VS)); |
7237 | break; |
7238 | } |
7239 | // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, |
7240 | // numrefs x valueid, n x (valueid)] |
7241 | // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, |
7242 | // numrefs x valueid, n x (valueid, hotness)] |
7243 | case bitc::FS_COMBINED: |
7244 | case bitc::FS_COMBINED_PROFILE: { |
7245 | unsigned ValueID = Record[0]; |
7246 | uint64_t ModuleId = Record[1]; |
7247 | uint64_t RawFlags = Record[2]; |
7248 | unsigned InstCount = Record[3]; |
7249 | uint64_t RawFunFlags = 0; |
7250 | uint64_t EntryCount = 0; |
7251 | unsigned NumRefs = Record[4]; |
7252 | unsigned NumRORefs = 0, NumWORefs = 0; |
7253 | int RefListStartIndex = 5; |
7254 | |
7255 | if (Version >= 4) { |
7256 | RawFunFlags = Record[4]; |
7257 | RefListStartIndex = 6; |
7258 | size_t NumRefsIndex = 5; |
7259 | if (Version >= 5) { |
7260 | unsigned NumRORefsOffset = 1; |
7261 | RefListStartIndex = 7; |
7262 | if (Version >= 6) { |
7263 | NumRefsIndex = 6; |
7264 | EntryCount = Record[5]; |
7265 | RefListStartIndex = 8; |
7266 | if (Version >= 7) { |
7267 | RefListStartIndex = 9; |
7268 | NumWORefs = Record[8]; |
7269 | NumRORefsOffset = 2; |
7270 | } |
7271 | } |
7272 | NumRORefs = Record[RefListStartIndex - NumRORefsOffset]; |
7273 | } |
7274 | NumRefs = Record[NumRefsIndex]; |
7275 | } |
7276 | |
7277 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
7278 | int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; |
7279 | assert(Record.size() >= RefListStartIndex + NumRefs &&(static_cast <bool> (Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 7280, __extension__ __PRETTY_FUNCTION__)) |
7280 | "Record size inconsistent with number of references")(static_cast <bool> (Record.size() >= RefListStartIndex + NumRefs && "Record size inconsistent with number of references" ) ? void (0) : __assert_fail ("Record.size() >= RefListStartIndex + NumRefs && \"Record size inconsistent with number of references\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 7280, __extension__ __PRETTY_FUNCTION__)); |
7281 | std::vector<ValueInfo> Refs = makeRefList( |
7282 | ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); |
7283 | bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); |
7284 | std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( |
7285 | ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), |
7286 | IsOldProfileFormat, HasProfile, false); |
7287 | ValueInfo VI = getValueInfoFromValueId(ValueID).first; |
7288 | setSpecialRefs(Refs, NumRORefs, NumWORefs); |
7289 | auto FS = std::make_unique<FunctionSummary>( |
7290 | Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount, |
7291 | std::move(Refs), std::move(Edges), std::move(PendingTypeTests), |
7292 | std::move(PendingTypeTestAssumeVCalls), |
7293 | std::move(PendingTypeCheckedLoadVCalls), |
7294 | std::move(PendingTypeTestAssumeConstVCalls), |
7295 | std::move(PendingTypeCheckedLoadConstVCalls), |
7296 | std::move(PendingParamAccesses)); |
7297 | LastSeenSummary = FS.get(); |
7298 | LastSeenGUID = VI.getGUID(); |
7299 | FS->setModulePath(ModuleIdMap[ModuleId]); |
7300 | TheIndex.addGlobalValueSummary(VI, std::move(FS)); |
7301 | break; |
7302 | } |
7303 | // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] |
7304 | // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as |
7305 | // they expect all aliasee summaries to be available. |
7306 | case bitc::FS_COMBINED_ALIAS: { |
7307 | unsigned ValueID = Record[0]; |
7308 | uint64_t ModuleId = Record[1]; |
7309 | uint64_t RawFlags = Record[2]; |
7310 | unsigned AliaseeValueId = Record[3]; |
7311 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
7312 | auto AS = std::make_unique<AliasSummary>(Flags); |
7313 | LastSeenSummary = AS.get(); |
7314 | AS->setModulePath(ModuleIdMap[ModuleId]); |
7315 | |
7316 | auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first; |
7317 | auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); |
7318 | AS->setAliasee(AliaseeVI, AliaseeInModule); |
7319 | |
7320 | ValueInfo VI = getValueInfoFromValueId(ValueID).first; |
7321 | LastSeenGUID = VI.getGUID(); |
7322 | TheIndex.addGlobalValueSummary(VI, std::move(AS)); |
7323 | break; |
7324 | } |
7325 | // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] |
7326 | case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { |
7327 | unsigned ValueID = Record[0]; |
7328 | uint64_t ModuleId = Record[1]; |
7329 | uint64_t RawFlags = Record[2]; |
7330 | unsigned RefArrayStart = 3; |
7331 | GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, |
7332 | /* WriteOnly */ false, |
7333 | /* Constant */ false, |
7334 | GlobalObject::VCallVisibilityPublic); |
7335 | auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); |
7336 | if (Version >= 5) { |
7337 | GVF = getDecodedGVarFlags(Record[3]); |
7338 | RefArrayStart = 4; |
7339 | } |
7340 | std::vector<ValueInfo> Refs = |
7341 | makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); |
7342 | auto FS = |
7343 | std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); |
7344 | LastSeenSummary = FS.get(); |
7345 | FS->setModulePath(ModuleIdMap[ModuleId]); |
7346 | ValueInfo VI = getValueInfoFromValueId(ValueID).first; |
7347 | LastSeenGUID = VI.getGUID(); |
7348 | TheIndex.addGlobalValueSummary(VI, std::move(FS)); |
7349 | break; |
7350 | } |
7351 | // FS_COMBINED_ORIGINAL_NAME: [original_name] |
7352 | case bitc::FS_COMBINED_ORIGINAL_NAME: { |
7353 | uint64_t OriginalName = Record[0]; |
7354 | if (!LastSeenSummary) |
7355 | return error("Name attachment that does not follow a combined record"); |
7356 | LastSeenSummary->setOriginalName(OriginalName); |
7357 | TheIndex.addOriginalName(LastSeenGUID, OriginalName); |
7358 | // Reset the LastSeenSummary |
7359 | LastSeenSummary = nullptr; |
7360 | LastSeenGUID = 0; |
7361 | break; |
7362 | } |
7363 | case bitc::FS_TYPE_TESTS: |
7364 | assert(PendingTypeTests.empty())(static_cast <bool> (PendingTypeTests.empty()) ? void ( 0) : __assert_fail ("PendingTypeTests.empty()", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 7364, __extension__ __PRETTY_FUNCTION__)); |
7365 | llvm::append_range(PendingTypeTests, Record); |
7366 | break; |
7367 | |
7368 | case bitc::FS_TYPE_TEST_ASSUME_VCALLS: |
7369 | assert(PendingTypeTestAssumeVCalls.empty())(static_cast <bool> (PendingTypeTestAssumeVCalls.empty( )) ? void (0) : __assert_fail ("PendingTypeTestAssumeVCalls.empty()" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 7369, __extension__ __PRETTY_FUNCTION__)); |
7370 | for (unsigned I = 0; I != Record.size(); I += 2) |
7371 | PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); |
7372 | break; |
7373 | |
7374 | case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: |
7375 | assert(PendingTypeCheckedLoadVCalls.empty())(static_cast <bool> (PendingTypeCheckedLoadVCalls.empty ()) ? void (0) : __assert_fail ("PendingTypeCheckedLoadVCalls.empty()" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 7375, __extension__ __PRETTY_FUNCTION__)); |
7376 | for (unsigned I = 0; I != Record.size(); I += 2) |
7377 | PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); |
7378 | break; |
7379 | |
7380 | case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: |
7381 | PendingTypeTestAssumeConstVCalls.push_back( |
7382 | {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); |
7383 | break; |
7384 | |
7385 | case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: |
7386 | PendingTypeCheckedLoadConstVCalls.push_back( |
7387 | {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); |
7388 | break; |
7389 | |
7390 | case bitc::FS_CFI_FUNCTION_DEFS: { |
7391 | std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); |
7392 | for (unsigned I = 0; I != Record.size(); I += 2) |
7393 | CfiFunctionDefs.insert( |
7394 | {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); |
7395 | break; |
7396 | } |
7397 | |
7398 | case bitc::FS_CFI_FUNCTION_DECLS: { |
7399 | std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); |
7400 | for (unsigned I = 0; I != Record.size(); I += 2) |
7401 | CfiFunctionDecls.insert( |
7402 | {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); |
7403 | break; |
7404 | } |
7405 | |
7406 | case bitc::FS_TYPE_ID: |
7407 | parseTypeIdSummaryRecord(Record, Strtab, TheIndex); |
7408 | break; |
7409 | |
7410 | case bitc::FS_TYPE_ID_METADATA: |
7411 | parseTypeIdCompatibleVtableSummaryRecord(Record); |
7412 | break; |
7413 | |
7414 | case bitc::FS_BLOCK_COUNT: |
7415 | TheIndex.addBlockCount(Record[0]); |
7416 | break; |
7417 | |
7418 | case bitc::FS_PARAM_ACCESS: { |
7419 | PendingParamAccesses = parseParamAccesses(Record); |
7420 | break; |
7421 | } |
7422 | } |
7423 | } |
7424 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 7424); |
7425 | } |
7426 | |
7427 | // Parse the module string table block into the Index. |
7428 | // This populates the ModulePathStringTable map in the index. |
7429 | Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { |
7430 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) |
7431 | return Err; |
7432 | |
7433 | SmallVector<uint64_t, 64> Record; |
7434 | |
7435 | SmallString<128> ModulePath; |
7436 | ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; |
7437 | |
7438 | while (true) { |
7439 | Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); |
7440 | if (!MaybeEntry) |
7441 | return MaybeEntry.takeError(); |
7442 | BitstreamEntry Entry = MaybeEntry.get(); |
7443 | |
7444 | switch (Entry.Kind) { |
7445 | case BitstreamEntry::SubBlock: // Handled for us already. |
7446 | case BitstreamEntry::Error: |
7447 | return error("Malformed block"); |
7448 | case BitstreamEntry::EndBlock: |
7449 | return Error::success(); |
7450 | case BitstreamEntry::Record: |
7451 | // The interesting case. |
7452 | break; |
7453 | } |
7454 | |
7455 | Record.clear(); |
7456 | Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); |
7457 | if (!MaybeRecord) |
7458 | return MaybeRecord.takeError(); |
7459 | switch (MaybeRecord.get()) { |
7460 | default: // Default behavior: ignore. |
7461 | break; |
7462 | case bitc::MST_CODE_ENTRY: { |
7463 | // MST_ENTRY: [modid, namechar x N] |
7464 | uint64_t ModuleId = Record[0]; |
7465 | |
7466 | if (convertToString(Record, 1, ModulePath)) |
7467 | return error("Invalid record"); |
7468 | |
7469 | LastSeenModule = TheIndex.addModule(ModulePath, ModuleId); |
7470 | ModuleIdMap[ModuleId] = LastSeenModule->first(); |
7471 | |
7472 | ModulePath.clear(); |
7473 | break; |
7474 | } |
7475 | /// MST_CODE_HASH: [5*i32] |
7476 | case bitc::MST_CODE_HASH: { |
7477 | if (Record.size() != 5) |
7478 | return error("Invalid hash length " + Twine(Record.size()).str()); |
7479 | if (!LastSeenModule) |
7480 | return error("Invalid hash that does not follow a module path"); |
7481 | int Pos = 0; |
7482 | for (auto &Val : Record) { |
7483 | assert(!(Val >> 32) && "Unexpected high bits set")(static_cast <bool> (!(Val >> 32) && "Unexpected high bits set" ) ? void (0) : __assert_fail ("!(Val >> 32) && \"Unexpected high bits set\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 7483, __extension__ __PRETTY_FUNCTION__)); |
7484 | LastSeenModule->second.second[Pos++] = Val; |
7485 | } |
7486 | // Reset LastSeenModule to avoid overriding the hash unexpectedly. |
7487 | LastSeenModule = nullptr; |
7488 | break; |
7489 | } |
7490 | } |
7491 | } |
7492 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 7492); |
7493 | } |
7494 | |
7495 | namespace { |
7496 | |
7497 | // FIXME: This class is only here to support the transition to llvm::Error. It |
7498 | // will be removed once this transition is complete. Clients should prefer to |
7499 | // deal with the Error value directly, rather than converting to error_code. |
7500 | class BitcodeErrorCategoryType : public std::error_category { |
7501 | const char *name() const noexcept override { |
7502 | return "llvm.bitcode"; |
7503 | } |
7504 | |
7505 | std::string message(int IE) const override { |
7506 | BitcodeError E = static_cast<BitcodeError>(IE); |
7507 | switch (E) { |
7508 | case BitcodeError::CorruptedBitcode: |
7509 | return "Corrupted bitcode"; |
7510 | } |
7511 | llvm_unreachable("Unknown error type!")::llvm::llvm_unreachable_internal("Unknown error type!", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 7511); |
7512 | } |
7513 | }; |
7514 | |
7515 | } // end anonymous namespace |
7516 | |
7517 | const std::error_category &llvm::BitcodeErrorCategory() { |
7518 | static BitcodeErrorCategoryType ErrorCategory; |
7519 | return ErrorCategory; |
7520 | } |
7521 | |
7522 | static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, |
7523 | unsigned Block, unsigned RecordID) { |
7524 | if (Error Err = Stream.EnterSubBlock(Block)) |
7525 | return std::move(Err); |
7526 | |
7527 | StringRef Strtab; |
7528 | while (true) { |
7529 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
7530 | if (!MaybeEntry) |
7531 | return MaybeEntry.takeError(); |
7532 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
7533 | |
7534 | switch (Entry.Kind) { |
7535 | case BitstreamEntry::EndBlock: |
7536 | return Strtab; |
7537 | |
7538 | case BitstreamEntry::Error: |
7539 | return error("Malformed block"); |
7540 | |
7541 | case BitstreamEntry::SubBlock: |
7542 | if (Error Err = Stream.SkipBlock()) |
7543 | return std::move(Err); |
7544 | break; |
7545 | |
7546 | case BitstreamEntry::Record: |
7547 | StringRef Blob; |
7548 | SmallVector<uint64_t, 1> Record; |
7549 | Expected<unsigned> MaybeRecord = |
7550 | Stream.readRecord(Entry.ID, Record, &Blob); |
7551 | if (!MaybeRecord) |
7552 | return MaybeRecord.takeError(); |
7553 | if (MaybeRecord.get() == RecordID) |
7554 | Strtab = Blob; |
7555 | break; |
7556 | } |
7557 | } |
7558 | } |
7559 | |
7560 | //===----------------------------------------------------------------------===// |
7561 | // External interface |
7562 | //===----------------------------------------------------------------------===// |
7563 | |
7564 | Expected<std::vector<BitcodeModule>> |
7565 | llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { |
7566 | auto FOrErr = getBitcodeFileContents(Buffer); |
7567 | if (!FOrErr) |
7568 | return FOrErr.takeError(); |
7569 | return std::move(FOrErr->Mods); |
7570 | } |
7571 | |
7572 | Expected<BitcodeFileContents> |
7573 | llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { |
7574 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); |
7575 | if (!StreamOrErr) |
7576 | return StreamOrErr.takeError(); |
7577 | BitstreamCursor &Stream = *StreamOrErr; |
7578 | |
7579 | BitcodeFileContents F; |
7580 | while (true) { |
7581 | uint64_t BCBegin = Stream.getCurrentByteNo(); |
7582 | |
7583 | // We may be consuming bitcode from a client that leaves garbage at the end |
7584 | // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to |
7585 | // the end that there cannot possibly be another module, stop looking. |
7586 | if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) |
7587 | return F; |
7588 | |
7589 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
7590 | if (!MaybeEntry) |
7591 | return MaybeEntry.takeError(); |
7592 | llvm::BitstreamEntry Entry = MaybeEntry.get(); |
7593 | |
7594 | switch (Entry.Kind) { |
7595 | case BitstreamEntry::EndBlock: |
7596 | case BitstreamEntry::Error: |
7597 | return error("Malformed block"); |
7598 | |
7599 | case BitstreamEntry::SubBlock: { |
7600 | uint64_t IdentificationBit = -1ull; |
7601 | if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { |
7602 | IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; |
7603 | if (Error Err = Stream.SkipBlock()) |
7604 | return std::move(Err); |
7605 | |
7606 | { |
7607 | Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); |
7608 | if (!MaybeEntry) |
7609 | return MaybeEntry.takeError(); |
7610 | Entry = MaybeEntry.get(); |
7611 | } |
7612 | |
7613 | if (Entry.Kind != BitstreamEntry::SubBlock || |
7614 | Entry.ID != bitc::MODULE_BLOCK_ID) |
7615 | return error("Malformed block"); |
7616 | } |
7617 | |
7618 | if (Entry.ID == bitc::MODULE_BLOCK_ID) { |
7619 | uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; |
7620 | if (Error Err = Stream.SkipBlock()) |
7621 | return std::move(Err); |
7622 | |
7623 | F.Mods.push_back({Stream.getBitcodeBytes().slice( |
7624 | BCBegin, Stream.getCurrentByteNo() - BCBegin), |
7625 | Buffer.getBufferIdentifier(), IdentificationBit, |
7626 | ModuleBit}); |
7627 | continue; |
7628 | } |
7629 | |
7630 | if (Entry.ID == bitc::STRTAB_BLOCK_ID) { |
7631 | Expected<StringRef> Strtab = |
7632 | readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); |
7633 | if (!Strtab) |
7634 | return Strtab.takeError(); |
7635 | // This string table is used by every preceding bitcode module that does |
7636 | // not have its own string table. A bitcode file may have multiple |
7637 | // string tables if it was created by binary concatenation, for example |
7638 | // with "llvm-cat -b". |
7639 | for (BitcodeModule &I : llvm::reverse(F.Mods)) { |
7640 | if (!I.Strtab.empty()) |
7641 | break; |
7642 | I.Strtab = *Strtab; |
7643 | } |
7644 | // Similarly, the string table is used by every preceding symbol table; |
7645 | // normally there will be just one unless the bitcode file was created |
7646 | // by binary concatenation. |
7647 | if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) |
7648 | F.StrtabForSymtab = *Strtab; |
7649 | continue; |
7650 | } |
7651 | |
7652 | if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { |
7653 | Expected<StringRef> SymtabOrErr = |
7654 | readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); |
7655 | if (!SymtabOrErr) |
7656 | return SymtabOrErr.takeError(); |
7657 | |
7658 | // We can expect the bitcode file to have multiple symbol tables if it |
7659 | // was created by binary concatenation. In that case we silently |
7660 | // ignore any subsequent symbol tables, which is fine because this is a |
7661 | // low level function. The client is expected to notice that the number |
7662 | // of modules in the symbol table does not match the number of modules |
7663 | // in the input file and regenerate the symbol table. |
7664 | if (F.Symtab.empty()) |
7665 | F.Symtab = *SymtabOrErr; |
7666 | continue; |
7667 | } |
7668 | |
7669 | if (Error Err = Stream.SkipBlock()) |
7670 | return std::move(Err); |
7671 | continue; |
7672 | } |
7673 | case BitstreamEntry::Record: |
7674 | if (Error E = Stream.skipRecord(Entry.ID).takeError()) |
7675 | return std::move(E); |
7676 | continue; |
7677 | } |
7678 | } |
7679 | } |
7680 | |
7681 | /// Get a lazy one-at-time loading module from bitcode. |
7682 | /// |
7683 | /// This isn't always used in a lazy context. In particular, it's also used by |
7684 | /// \a parseModule(). If this is truly lazy, then we need to eagerly pull |
7685 | /// in forward-referenced functions from block address references. |
7686 | /// |
7687 | /// \param[in] MaterializeAll Set to \c true if we should materialize |
7688 | /// everything. |
7689 | Expected<std::unique_ptr<Module>> |
7690 | BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, |
7691 | bool ShouldLazyLoadMetadata, bool IsImporting, |
7692 | DataLayoutCallbackTy DataLayoutCallback) { |
7693 | BitstreamCursor Stream(Buffer); |
7694 | |
7695 | std::string ProducerIdentification; |
7696 | if (IdentificationBit != -1ull) { |
7697 | if (Error JumpFailed = Stream.JumpToBit(IdentificationBit)) |
7698 | return std::move(JumpFailed); |
7699 | if (Error E = |
7700 | readIdentificationBlock(Stream).moveInto(ProducerIdentification)) |
7701 | return std::move(E); |
7702 | } |
7703 | |
7704 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) |
7705 | return std::move(JumpFailed); |
7706 | auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, |
7707 | Context); |
7708 | |
7709 | std::unique_ptr<Module> M = |
7710 | std::make_unique<Module>(ModuleIdentifier, Context); |
7711 | M->setMaterializer(R); |
7712 | |
7713 | // Delay parsing Metadata if ShouldLazyLoadMetadata is true. |
7714 | if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, |
7715 | IsImporting, DataLayoutCallback)) |
7716 | return std::move(Err); |
7717 | |
7718 | if (MaterializeAll) { |
7719 | // Read in the entire module, and destroy the BitcodeReader. |
7720 | if (Error Err = M->materializeAll()) |
7721 | return std::move(Err); |
7722 | } else { |
7723 | // Resolve forward references from blockaddresses. |
7724 | if (Error Err = R->materializeForwardReferencedFunctions()) |
7725 | return std::move(Err); |
7726 | } |
7727 | return std::move(M); |
7728 | } |
7729 | |
7730 | Expected<std::unique_ptr<Module>> |
7731 | BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, |
7732 | bool IsImporting) { |
7733 | return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting, |
7734 | [](StringRef) { return None; }); |
7735 | } |
7736 | |
7737 | // Parse the specified bitcode buffer and merge the index into CombinedIndex. |
7738 | // We don't use ModuleIdentifier here because the client may need to control the |
7739 | // module path used in the combined summary (e.g. when reading summaries for |
7740 | // regular LTO modules). |
7741 | Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex, |
7742 | StringRef ModulePath, uint64_t ModuleId) { |
7743 | BitstreamCursor Stream(Buffer); |
7744 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) |
7745 | return JumpFailed; |
7746 | |
7747 | ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, |
7748 | ModulePath, ModuleId); |
7749 | return R.parseModule(); |
7750 | } |
7751 | |
7752 | // Parse the specified bitcode buffer, returning the function info index. |
7753 | Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { |
7754 | BitstreamCursor Stream(Buffer); |
7755 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) |
7756 | return std::move(JumpFailed); |
7757 | |
7758 | auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); |
7759 | ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, |
7760 | ModuleIdentifier, 0); |
7761 | |
7762 | if (Error Err = R.parseModule()) |
7763 | return std::move(Err); |
7764 | |
7765 | return std::move(Index); |
7766 | } |
7767 | |
7768 | static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream, |
7769 | unsigned ID) { |
7770 | if (Error Err = Stream.EnterSubBlock(ID)) |
7771 | return std::move(Err); |
7772 | SmallVector<uint64_t, 64> Record; |
7773 | |
7774 | while (true) { |
7775 | BitstreamEntry Entry; |
7776 | if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry)) |
7777 | return std::move(E); |
7778 | |
7779 | switch (Entry.Kind) { |
7780 | case BitstreamEntry::SubBlock: // Handled for us already. |
7781 | case BitstreamEntry::Error: |
7782 | return error("Malformed block"); |
7783 | case BitstreamEntry::EndBlock: |
7784 | // If no flags record found, conservatively return true to mimic |
7785 | // behavior before this flag was added. |
7786 | return true; |
7787 | case BitstreamEntry::Record: |
7788 | // The interesting case. |
7789 | break; |
7790 | } |
7791 | |
7792 | // Look for the FS_FLAGS record. |
7793 | Record.clear(); |
7794 | Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); |
7795 | if (!MaybeBitCode) |
7796 | return MaybeBitCode.takeError(); |
7797 | switch (MaybeBitCode.get()) { |
7798 | default: // Default behavior: ignore. |
7799 | break; |
7800 | case bitc::FS_FLAGS: { // [flags] |
7801 | uint64_t Flags = Record[0]; |
7802 | // Scan flags. |
7803 | assert(Flags <= 0xff && "Unexpected bits in flag")(static_cast <bool> (Flags <= 0xff && "Unexpected bits in flag" ) ? void (0) : __assert_fail ("Flags <= 0xff && \"Unexpected bits in flag\"" , "llvm/lib/Bitcode/Reader/BitcodeReader.cpp", 7803, __extension__ __PRETTY_FUNCTION__)); |
7804 | |
7805 | return Flags & 0x8; |
7806 | } |
7807 | } |
7808 | } |
7809 | llvm_unreachable("Exit infinite loop")::llvm::llvm_unreachable_internal("Exit infinite loop", "llvm/lib/Bitcode/Reader/BitcodeReader.cpp" , 7809); |
7810 | } |
7811 | |
7812 | // Check if the given bitcode buffer contains a global value summary block. |
7813 | Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { |
7814 | BitstreamCursor Stream(Buffer); |
7815 | if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) |
7816 | return std::move(JumpFailed); |
7817 | |
7818 | if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) |
7819 | return std::move(Err); |
7820 | |
7821 | while (true) { |
7822 | llvm::BitstreamEntry Entry; |
7823 | if (Error E = Stream.advance().moveInto(Entry)) |
7824 | return std::move(E); |
7825 | |
7826 | switch (Entry.Kind) { |
7827 | case BitstreamEntry::Error: |
7828 | return error("Malformed block"); |
7829 | case BitstreamEntry::EndBlock: |
7830 | return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false, |
7831 | /*EnableSplitLTOUnit=*/false}; |
7832 | |
7833 | case BitstreamEntry::SubBlock: |
7834 | if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { |
7835 | Expected<bool> EnableSplitLTOUnit = |
7836 | getEnableSplitLTOUnitFlag(Stream, Entry.ID); |
7837 | if (!EnableSplitLTOUnit) |
7838 | return EnableSplitLTOUnit.takeError(); |
7839 | return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true, |
7840 | *EnableSplitLTOUnit}; |
7841 | } |
7842 | |
7843 | if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) { |
7844 | Expected<bool> EnableSplitLTOUnit = |
7845 | getEnableSplitLTOUnitFlag(Stream, Entry.ID); |
7846 | if (!EnableSplitLTOUnit) |
7847 | return EnableSplitLTOUnit.takeError(); |
7848 | return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true, |
7849 | *EnableSplitLTOUnit}; |
7850 | } |
7851 | |
7852 | // Ignore other sub-blocks. |
7853 | if (Error Err = Stream.SkipBlock()) |
7854 | return std::move(Err); |
7855 | continue; |
7856 | |
7857 | case BitstreamEntry::Record: |
7858 | if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) |
7859 | continue; |
7860 | else |
7861 | return StreamFailed.takeError(); |
7862 | } |
7863 | } |
7864 | } |
7865 | |
7866 | static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { |
7867 | Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); |
7868 | if (!MsOrErr) |
7869 | return MsOrErr.takeError(); |
7870 | |
7871 | if (MsOrErr->size() != 1) |
7872 | return error("Expected a single module"); |
7873 | |
7874 | return (*MsOrErr)[0]; |
7875 | } |
7876 | |
7877 | Expected<std::unique_ptr<Module>> |
7878 | llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, |
7879 | bool ShouldLazyLoadMetadata, bool IsImporting) { |
7880 | Expected<BitcodeModule> BM = getSingleModule(Buffer); |
7881 | if (!BM) |
7882 | return BM.takeError(); |
7883 | |
7884 | return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting); |
7885 | } |
7886 | |
7887 | Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( |
7888 | std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, |
7889 | bool ShouldLazyLoadMetadata, bool IsImporting) { |
7890 | auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, |
7891 | IsImporting); |
7892 | if (MOrErr) |
7893 | (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); |
7894 | return MOrErr; |
7895 | } |
7896 | |
7897 | Expected<std::unique_ptr<Module>> |
7898 | BitcodeModule::parseModule(LLVMContext &Context, |
7899 | DataLayoutCallbackTy DataLayoutCallback) { |
7900 | return getModuleImpl(Context, true, false, false, DataLayoutCallback); |
7901 | // TODO: Restore the use-lists to the in-memory state when the bitcode was |
7902 | // written. We must defer until the Module has been fully materialized. |
7903 | } |
7904 | |
7905 | Expected<std::unique_ptr<Module>> |
7906 | llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, |
7907 | DataLayoutCallbackTy DataLayoutCallback) { |
7908 | Expected<BitcodeModule> BM = getSingleModule(Buffer); |
7909 | if (!BM) |
7910 | return BM.takeError(); |
7911 | |
7912 | return BM->parseModule(Context, DataLayoutCallback); |
7913 | } |
7914 | |
7915 | Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { |
7916 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); |
7917 | if (!StreamOrErr) |
7918 | return StreamOrErr.takeError(); |
7919 | |
7920 | return readTriple(*StreamOrErr); |
7921 | } |
7922 | |
7923 | Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { |
7924 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); |
7925 | if (!StreamOrErr) |
7926 | return StreamOrErr.takeError(); |
7927 | |
7928 | return hasObjCCategory(*StreamOrErr); |
7929 | } |
7930 | |
7931 | Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { |
7932 | Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); |
7933 | if (!StreamOrErr) |
7934 | return StreamOrErr.takeError(); |
7935 | |
7936 | return readIdentificationCode(*StreamOrErr); |
7937 | } |
7938 | |
7939 | Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, |
7940 | ModuleSummaryIndex &CombinedIndex, |
7941 | uint64_t ModuleId) { |
7942 | Expected<BitcodeModule> BM = getSingleModule(Buffer); |
7943 | if (!BM) |
7944 | return BM.takeError(); |
7945 | |
7946 | return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId); |
7947 | } |
7948 | |
7949 | Expected<std::unique_ptr<ModuleSummaryIndex>> |
7950 | llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { |
7951 | Expected<BitcodeModule> BM = getSingleModule(Buffer); |
7952 | if (!BM) |
7953 | return BM.takeError(); |
7954 | |
7955 | return BM->getSummary(); |
7956 | } |
7957 | |
7958 | Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { |
7959 | Expected<BitcodeModule> BM = getSingleModule(Buffer); |
7960 | if (!BM) |
7961 | return BM.takeError(); |
7962 | |
7963 | return BM->getLTOInfo(); |
7964 | } |
7965 | |
7966 | Expected<std::unique_ptr<ModuleSummaryIndex>> |
7967 | llvm::getModuleSummaryIndexForFile(StringRef Path, |
7968 | bool IgnoreEmptyThinLTOIndexFile) { |
7969 | ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = |
7970 | MemoryBuffer::getFileOrSTDIN(Path); |
7971 | if (!FileOrErr) |
7972 | return errorCodeToError(FileOrErr.getError()); |
7973 | if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) |
7974 | return nullptr; |
7975 | return getModuleSummaryIndex(**FileOrErr); |
7976 | } |