llvm.org GIT mirror llvm / 7a1fc2d
Use diagnostic handler in the LLVMContext This patch converts code that has access to a LLVMContext to not take a diagnostic handler. This has a few advantages * It is easier to use a consistent diagnostic handler in a single program. * Less clutter since we are not passing a handler around. It does make it a bit awkward to implement some C APIs that return a diagnostic string. I will propose new versions of these APIs and deprecate the current ones. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@255571 91177308-0d34-0410-b5e6-96231b3b80d8 Rafael Espindola 4 years ago
18 changed file(s) with 165 addition(s) and 199 deletion(s). Raw diff Collapse all Expand all
3636 ErrorOr>
3737 getLazyBitcodeModule(std::unique_ptr &&Buffer,
3838 LLVMContext &Context,
39 DiagnosticHandlerFunction DiagnosticHandler = nullptr,
4039 bool ShouldLazyLoadMetadata = false);
4140
4241 /// Read the header of the specified stream and prepare for lazy
4342 /// deserialization and streaming of function bodies.
44 ErrorOr> getStreamedBitcodeModule(
45 StringRef Name, std::unique_ptr Streamer,
46 LLVMContext &Context,
47 DiagnosticHandlerFunction DiagnosticHandler = nullptr);
43 ErrorOr>
44 getStreamedBitcodeModule(StringRef Name,
45 std::unique_ptr Streamer,
46 LLVMContext &Context);
4847
4948 /// Read the header of the specified bitcode buffer and extract just the
5049 /// triple information. If successful, this returns a string. On error, this
5150 /// returns "".
52 std::string
53 getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
54 DiagnosticHandlerFunction DiagnosticHandler = nullptr);
51 std::string getBitcodeTargetTriple(MemoryBufferRef Buffer,
52 LLVMContext &Context);
5553
5654 /// Read the header of the specified bitcode buffer and extract just the
5755 /// producer string information. If successful, this returns a string. On
5856 /// error, this returns "".
59 std::string getBitcodeProducerString(
60 MemoryBufferRef Buffer, LLVMContext &Context,
61 DiagnosticHandlerFunction DiagnosticHandler = nullptr);
57 std::string getBitcodeProducerString(MemoryBufferRef Buffer,
58 LLVMContext &Context);
6259
6360 /// Read the specified bitcode file, returning the module.
64 ErrorOr>
65 parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
66 DiagnosticHandlerFunction DiagnosticHandler = nullptr);
61 ErrorOr> parseBitcodeFile(MemoryBufferRef Buffer,
62 LLVMContext &Context);
6763
6864 /// Check if the given bitcode buffer contains a function summary block.
6965 bool hasFunctionSummary(MemoryBufferRef Buffer,
7470 /// the index. Otherwise skip the function summary section, and only create
7571 /// an index object with a map from function name to function summary offset.
7672 /// The index is used to perform lazy function summary reading later.
77 ErrorOr> getFunctionInfoIndex(
78 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
79 bool IsLazy = false);
73 ErrorOr>
74 getFunctionInfoIndex(MemoryBufferRef Buffer,
75 DiagnosticHandlerFunction DiagnosticHandler,
76 bool IsLazy = false);
8077
8178 /// This method supports lazy reading of function summary data from the
8279 /// combined index during function importing. When reading the combined index
1111
1212 #include "llvm/ADT/ArrayRef.h"
1313 #include "llvm/ADT/DenseSet.h"
14 #include "llvm/IR/DiagnosticInfo.h"
1514
1615 namespace llvm {
1716 class GlobalValue;
5352 bool hasType(StructType *Ty);
5453 };
5554
56 IRMover(Module &M, DiagnosticHandlerFunction DiagnosticHandler);
55 IRMover(Module &M);
5756
5857 typedef std::function ValueAdder;
5958 /// Move in the provide values. The source is destroyed.
6261 std::function AddLazyFor);
6362 Module &getModule() { return Composite; }
6463
65 DiagnosticHandlerFunction getDiagnosticHandler() const {
66 return DiagnosticHandler;
67 }
68
6964 private:
7065 Module &Composite;
7166 IdentifiedStructTypeSet IdentifiedStructTypes;
72 DiagnosticHandlerFunction DiagnosticHandler;
7367 };
7468
7569 } // End llvm namespace
99 #ifndef LLVM_LINKER_LINKER_H
1010 #define LLVM_LINKER_LINKER_H
1111
12 #include "llvm/IR/DiagnosticInfo.h"
1312 #include "llvm/IR/FunctionInfo.h"
1413 #include "llvm/Linker/IRMover.h"
1514
3332 InternalizeLinkedSymbols = (1 << 2)
3433 };
3534
36 Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler);
35 Linker(Module &M);
3736
3837 /// \brief Link \p Src into the composite. The source is destroyed.
3938 ///
4948 DenseSet *FunctionsToImport = nullptr);
5049
5150 static bool linkModules(Module &Dest, Module &Src,
52 DiagnosticHandlerFunction DiagnosticHandler,
5351 unsigned Flags = Flags::None);
5452
55 DiagnosticHandlerFunction getDiagnosticHandler() const {
56 return Mover.getDiagnosticHandler();
57 }
5853 };
5954
6055 /// Create a new module with exported local functions renamed and promoted
6156 /// for ThinLTO.
62 std::unique_ptr
63 renameModuleForThinLTO(std::unique_ptr &M,
64 const FunctionInfoIndex *Index,
65 DiagnosticHandlerFunction DiagnosticHandler);
57 std::unique_ptr renameModuleForThinLTO(std::unique_ptr &M,
58 const FunctionInfoIndex *Index);
6659
6760 } // End llvm namespace
6861
99 #ifndef LLVM_FUNCTIONIMPORT_H
1010 #define LLVM_FUNCTIONIMPORT_H
1111
12 #include "llvm/IR/DiagnosticInfo.h"
1312 #include "llvm/ADT/StringMap.h"
1413
1514 namespace llvm {
2423 /// The summaries index used to trigger importing.
2524 const FunctionInfoIndex &Index;
2625
27 /// Diagnostic will be sent to this handler.
28 DiagnosticHandlerFunction DiagnosticHandler;
29
3026 /// Factory function to load a Module for a given identifier
3127 std::function(StringRef Identifier)> ModuleLoader;
3228
3430 /// Create a Function Importer.
3531 FunctionImporter(
3632 const FunctionInfoIndex &Index,
37 DiagnosticHandlerFunction DiagnosticHandler,
3833 std::function(StringRef Identifier)> ModuleLoader)
39 : Index(Index), DiagnosticHandler(DiagnosticHandler),
40 ModuleLoader(ModuleLoader) {}
34 : Index(Index), ModuleLoader(ModuleLoader) {}
4135
4236 /// Import functions in Module \p M based on the summary informations.
4337 bool importFunctions(Module &M);
2727 OutMessage);
2828 }
2929
30 static void diagnosticHandler(const DiagnosticInfo &DI, void *C) {
31 auto *Message = reinterpret_cast(C);
32 raw_string_ostream Stream(*Message);
33 DiagnosticPrinterRawOStream DP(Stream);
34 DI.print(DP);
35 }
36
3037 LLVMBool LLVMParseBitcodeInContext(LLVMContextRef ContextRef,
3138 LLVMMemoryBufferRef MemBuf,
3239 LLVMModuleRef *OutModule,
3441 MemoryBufferRef Buf = unwrap(MemBuf)->getMemBufferRef();
3542 LLVMContext &Ctx = *unwrap(ContextRef);
3643
44 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
45 Ctx.getDiagnosticHandler();
46 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
3747 std::string Message;
38 raw_string_ostream Stream(Message);
39 DiagnosticPrinterRawOStream DP(Stream);
48 Ctx.setDiagnosticHandler(diagnosticHandler, &Message, true);
4049
41 ErrorOr> ModuleOrErr = parseBitcodeFile(
42 Buf, Ctx, [&](const DiagnosticInfo &DI) { DI.print(DP); });
50 ErrorOr> ModuleOrErr = parseBitcodeFile(Buf, Ctx);
51
52 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext, true);
53
4354 if (ModuleOrErr.getError()) {
44 if (OutMessage) {
45 Stream.flush();
55 if (OutMessage)
4656 *OutMessage = strdup(Message.c_str());
47 }
4857 *OutModule = wrap((Module*)nullptr);
4958 return 1;
5059 }
131131
132132 class BitcodeReader : public GVMaterializer {
133133 LLVMContext &Context;
134 DiagnosticHandlerFunction DiagnosticHandler;
135134 Module *TheModule = nullptr;
136135 std::unique_ptr Buffer;
137136 std::unique_ptr StreamFile;
238237 std::error_code error(BitcodeError E);
239238 std::error_code error(const Twine &Message);
240239
241 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
242 DiagnosticHandlerFunction DiagnosticHandler);
243 BitcodeReader(LLVMContext &Context,
244 DiagnosticHandlerFunction DiagnosticHandler);
240 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
241 BitcodeReader(LLVMContext &Context);
245242 ~BitcodeReader() override { freeState(); }
246243
247244 std::error_code materializeForwardReferencedFunctions();
517514 return error(DiagnosticHandler, EC, EC.message());
518515 }
519516
520 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
517 static std::error_code error(LLVMContext &Context, std::error_code EC,
521518 const Twine &Message) {
522 return error(DiagnosticHandler,
523 make_error_code(BitcodeError::CorruptedBitcode), Message);
519 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
520 Message);
521 }
522
523 static std::error_code error(LLVMContext &Context, std::error_code EC) {
524 return error(Context, EC, EC.message());
525 }
526
527 static std::error_code error(LLVMContext &Context, const Twine &Message) {
528 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
529 Message);
524530 }
525531
526532 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
527533 if (!ProducerIdentification.empty()) {
528 return ::error(DiagnosticHandler, make_error_code(E),
534 return ::error(Context, make_error_code(E),
529535 Message + " (Producer: '" + ProducerIdentification +
530536 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
531537 }
532 return ::error(DiagnosticHandler, make_error_code(E), Message);
538 return ::error(Context, make_error_code(E), Message);
533539 }
534540
535541 std::error_code BitcodeReader::error(const Twine &Message) {
536542 if (!ProducerIdentification.empty()) {
537 return ::error(DiagnosticHandler,
538 make_error_code(BitcodeError::CorruptedBitcode),
543 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
539544 Message + " (Producer: '" + ProducerIdentification +
540545 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
541546 }
542 return ::error(DiagnosticHandler,
543 make_error_code(BitcodeError::CorruptedBitcode), Message);
547 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
548 Message);
544549 }
545550
546551 std::error_code BitcodeReader::error(BitcodeError E) {
547 return ::error(DiagnosticHandler, make_error_code(E));
548 }
549
550 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
551 LLVMContext &C) {
552 if (F)
553 return F;
554 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
555 }
556
557 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
558 DiagnosticHandlerFunction DiagnosticHandler)
559 : Context(Context),
560 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
561 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
562
563 BitcodeReader::BitcodeReader(LLVMContext &Context,
564 DiagnosticHandlerFunction DiagnosticHandler)
565 : Context(Context),
566 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
567 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
552 return ::error(Context, make_error_code(E));
553 }
554
555 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
556 : Context(Context), Buffer(Buffer), ValueList(Context),
557 MDValueList(Context) {}
558
559 BitcodeReader::BitcodeReader(LLVMContext &Context)
560 : Context(Context), Buffer(nullptr), ValueList(Context),
561 MDValueList(Context) {}
568562
569563 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
570564 if (WillMaterializeAllForwardRefs)
38973891 }
38983892 }
38993893
3900 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3901 Type *ValType, Type *PtrType) {
3894 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3895 LLVMContext &Context = PtrType->getContext();
39023896 if (!isa(PtrType))
3903 return error(DH, "Load/Store operand is not a pointer type");
3897 return error(Context, "Load/Store operand is not a pointer type");
39043898 Type *ElemType = cast(PtrType)->getElementType();
39053899
39063900 if (ValType && ValType != ElemType)
3907 return error(DH, "Explicit load/store type does not match pointee type of "
3908 "pointer operand");
3901 return error(Context, "Explicit load/store type does not match pointee "
3902 "type of pointer operand");
39093903 if (!PointerType::isLoadableOrStorableType(ElemType))
3910 return error(DH, "Cannot load/store from pointer");
3904 return error(Context, "Cannot load/store from pointer");
39113905 return std::error_code();
39123906 }
39133907
48214815 Type *Ty = nullptr;
48224816 if (OpNum + 3 == Record.size())
48234817 Ty = getTypeByID(Record[OpNum++]);
4824 if (std::error_code EC =
4825 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4818 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
48264819 return EC;
48274820 if (!Ty)
48284821 Ty = cast(Op->getType())->getElementType();
48464839 Type *Ty = nullptr;
48474840 if (OpNum + 5 == Record.size())
48484841 Ty = getTypeByID(Record[OpNum++]);
4849 if (std::error_code EC =
4850 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4842 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
48514843 return EC;
48524844 if (!Ty)
48534845 Ty = cast(Op->getType())->getElementType();
48814873 OpNum + 2 != Record.size())
48824874 return error("Invalid record");
48834875
4884 if (std::error_code EC = typeCheckLoadStoreInst(
4885 DiagnosticHandler, Val->getType(), Ptr->getType()))
4876 if (std::error_code EC =
4877 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
48864878 return EC;
48874879 unsigned Align;
48884880 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
49054897 OpNum + 4 != Record.size())
49064898 return error("Invalid record");
49074899
4908 if (std::error_code EC = typeCheckLoadStoreInst(
4909 DiagnosticHandler, Val->getType(), Ptr->getType()))
4900 if (std::error_code EC =
4901 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
49104902 return EC;
49114903 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
49124904 if (Ordering == NotAtomic || Ordering == Acquire ||
49434935 return error("Invalid record");
49444936 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
49454937
4946 if (std::error_code EC = typeCheckLoadStoreInst(
4947 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4938 if (std::error_code EC =
4939 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
49484940 return EC;
49494941 AtomicOrdering FailureOrdering;
49504942 if (Record.size() < 7)
58625854 static ErrorOr>
58635855 getLazyBitcodeModuleImpl(std::unique_ptr &&Buffer,
58645856 LLVMContext &Context, bool MaterializeAll,
5865 DiagnosticHandlerFunction DiagnosticHandler,
58665857 bool ShouldLazyLoadMetadata = false) {
5867 BitcodeReader *R =
5868 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5858 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
58695859
58705860 ErrorOr> Ret =
58715861 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
58775867 return Ret;
58785868 }
58795869
5880 ErrorOr> llvm::getLazyBitcodeModule(
5881 std::unique_ptr &&Buffer, LLVMContext &Context,
5882 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5870 ErrorOr>
5871 llvm::getLazyBitcodeModule(std::unique_ptr &&Buffer,
5872 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
58835873 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5884 DiagnosticHandler, ShouldLazyLoadMetadata);
5885 }
5886
5887 ErrorOr> llvm::getStreamedBitcodeModule(
5888 StringRef Name, std::unique_ptr Streamer,
5889 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5874 ShouldLazyLoadMetadata);
5875 }
5876
5877 ErrorOr>
5878 llvm::getStreamedBitcodeModule(StringRef Name,
5879 std::unique_ptr Streamer,
5880 LLVMContext &Context) {
58905881 std::unique_ptr M = make_unique(Name, Context);
5891 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5882 BitcodeReader *R = new BitcodeReader(Context);
58925883
58935884 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
58945885 false);
58955886 }
58965887
5897 ErrorOr>
5898 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5899 DiagnosticHandlerFunction DiagnosticHandler) {
5888 ErrorOr> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5889 LLVMContext &Context) {
59005890 std::unique_ptr Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5901 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5902 DiagnosticHandler);
5891 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
59035892 // TODO: Restore the use-lists to the in-memory state when the bitcode was
59045893 // written. We must defer until the Module has been fully materialized.
59055894 }
59065895
5907 std::string
5908 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5909 DiagnosticHandlerFunction DiagnosticHandler) {
5896 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
5897 LLVMContext &Context) {
59105898 std::unique_ptr Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5911 auto R = llvm::make_unique(Buf.release(), Context,
5912 DiagnosticHandler);
5899 auto R = llvm::make_unique(Buf.release(), Context);
59135900 ErrorOr Triple = R->parseTriple();
59145901 if (Triple.getError())
59155902 return "";
59165903 return Triple.get();
59175904 }
59185905
5919 std::string
5920 llvm::getBitcodeProducerString(MemoryBufferRef Buffer, LLVMContext &Context,
5921 DiagnosticHandlerFunction DiagnosticHandler) {
5906 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
5907 LLVMContext &Context) {
59225908 std::unique_ptr Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5923 BitcodeReader R(Buf.release(), Context, DiagnosticHandler);
5909 BitcodeReader R(Buf.release(), Context);
59245910 ErrorOr ProducerString = R.parseIdentificationBlock();
59255911 if (ProducerString.getError())
59265912 return "";
6565
6666 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
6767 : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
68 IRLinker(new Linker(*MergedModule, [this](const DiagnosticInfo &DI) {
69 MergedModule->getContext().diagnose(DI);
70 })) {
68 IRLinker(new Linker(*MergedModule)) {
7169 initializeLTOPasses();
7270 }
7371
123121 AsmUndefinedRefs.clear();
124122
125123 MergedModule = Mod->takeModule();
126 IRLinker = llvm::make_unique(*MergedModule,
127 IRLinker->getDiagnosticHandler());
124 IRLinker = make_unique(*MergedModule);
128125
129126 const std::vector &Undefs = Mod->getAsmUndefinedRefs();
130127 for (int I = 0, E = Undefs.size(); I != E; ++I)
171171 // Parse lazily.
172172 std::unique_ptr LightweightBuf =
173173 MemoryBuffer::getMemBuffer(*MBOrErr, false);
174 ErrorOr> M =
175 getLazyBitcodeModule(std::move(LightweightBuf), Context, nullptr,
176 true /*ShouldLazyLoadMetadata*/);
174 ErrorOr> M = getLazyBitcodeModule(
175 std::move(LightweightBuf), Context, true /*ShouldLazyLoadMetadata*/);
177176 if (std::error_code EC = M.getError())
178177 return EC;
179178 return std::move(*M);
386386 Worklist.push_back(GV);
387387 }
388388
389 DiagnosticHandlerFunction DiagnosticHandler;
390
391389 /// Set to true when all global value body linking is complete (including
392390 /// lazy linking). Used to prevent metadata linking from creating new
393391 /// references.
401399
402400 /// Helper method for setting a message and returning an error code.
403401 bool emitError(const Twine &Message) {
404 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
402 SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
405403 HasError = true;
406404 return true;
407405 }
408406
409407 void emitWarning(const Twine &Message) {
410 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
408 SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
411409 }
412410
413411 /// Given a global in the source module, return the global in the
457455
458456 public:
459457 IRLinker(Module &DstM, IRMover::IdentifiedStructTypeSet &Set, Module &SrcM,
460 DiagnosticHandlerFunction DiagnosticHandler,
461458 ArrayRef ValuesToLink,
462459 std::function AddLazyFor)
463460 : DstM(DstM), SrcM(SrcM), AddLazyFor(AddLazyFor), TypeMap(Set),
464 GValMaterializer(this), LValMaterializer(this),
465 DiagnosticHandler(DiagnosticHandler) {
461 GValMaterializer(this), LValMaterializer(this) {
466462 for (GlobalValue *GV : ValuesToLink)
467463 maybeAdd(GV);
468464 }
13741370 return *I == Ty;
13751371 }
13761372
1377 IRMover::IRMover(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
1378 : Composite(M), DiagnosticHandler(DiagnosticHandler) {
1373 IRMover::IRMover(Module &M) : Composite(M) {
13791374 TypeFinder StructTypes;
13801375 StructTypes.run(M, true);
13811376 for (StructType *Ty : StructTypes) {
13891384 bool IRMover::move(
13901385 Module &Src, ArrayRef ValuesToLink,
13911386 std::function AddLazyFor) {
1392 IRLinker TheLinker(Composite, IdentifiedStructTypes, Src, DiagnosticHandler,
1393 ValuesToLink, AddLazyFor);
1387 IRLinker TheLinker(Composite, IdentifiedStructTypes, Src, ValuesToLink,
1388 AddLazyFor);
13941389 bool RetCode = TheLinker.run();
13951390 Composite.dropTriviallyDeadConstantArrays();
13961391 return RetCode;
1616 #include "llvm/ADT/SetVector.h"
1717 #include "llvm/ADT/StringSet.h"
1818 #include "llvm/IR/DiagnosticPrinter.h"
19 #include "llvm/IR/LLVMContext.h"
1920 using namespace llvm;
2021
2122 namespace {
6667
6768 /// Should we have mover and linker error diag info?
6869 bool emitError(const Twine &Message) {
69 Mover.getDiagnosticHandler()(LinkDiagnosticInfo(DS_Error, Message));
70 SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
7071 return true;
7172 }
7273
785786 return false;
786787 }
787788
788 Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
789 : Mover(M, DiagnosticHandler) {}
789 Linker::Linker(Module &M) : Mover(M) {}
790790
791791 bool Linker::linkInModule(Module &Src, unsigned Flags,
792792 const FunctionInfoIndex *Index,
804804 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
805805 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
806806 /// relied on to be consistent.
807 bool Linker::linkModules(Module &Dest, Module &Src,
808 DiagnosticHandlerFunction DiagnosticHandler,
809 unsigned Flags) {
810 Linker L(Dest, DiagnosticHandler);
807 bool Linker::linkModules(Module &Dest, Module &Src, unsigned Flags) {
808 Linker L(Dest);
811809 return L.linkInModule(Src, Flags);
812810 }
813811
814812 std::unique_ptr
815813 llvm::renameModuleForThinLTO(std::unique_ptr &M,
816 const FunctionInfoIndex *Index,
817 DiagnosticHandlerFunction DiagnosticHandler) {
814 const FunctionInfoIndex *Index) {
818815 std::unique_ptr RenamedModule(
819816 new llvm::Module(M->getModuleIdentifier(), M->getContext()));
820 Linker L(*RenamedModule.get(), DiagnosticHandler);
817 Linker L(*RenamedModule.get());
821818 if (L.linkInModule(*M.get(), llvm::Linker::Flags::None, Index))
822819 return nullptr;
823820 return RenamedModule;
827824 // C API.
828825 //===----------------------------------------------------------------------===//
829826
827 static void diagnosticHandler(const DiagnosticInfo &DI, void *C) {
828 auto *Message = reinterpret_cast(C);
829 raw_string_ostream Stream(*Message);
830 DiagnosticPrinterRawOStream DP(Stream);
831 DI.print(DP);
832 }
833
830834 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
831835 LLVMLinkerMode Unused, char **OutMessages) {
832836 Module *D = unwrap(Dest);
837 LLVMContext &Ctx = D->getContext();
838
839 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
840 Ctx.getDiagnosticHandler();
841 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
833842 std::string Message;
834 raw_string_ostream Stream(Message);
835 DiagnosticPrinterRawOStream DP(Stream);
836
837 LLVMBool Result = Linker::linkModules(
838 *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
839
840 if (OutMessages && Result) {
841 Stream.flush();
843 Ctx.setDiagnosticHandler(diagnosticHandler, &Message, true);
844
845 LLVMBool Result = Linker::linkModules(*D, *unwrap(Src));
846
847 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext, true);
848
849 if (OutMessages && Result)
842850 *OutMessages = strdup(Message.c_str());
843 }
844851 return Result;
845852 }
308308 MemoryBuffer::getMemBuffer(BCOrErr.get(), false));
309309
310310 ErrorOr> MOrErr =
311 getLazyBitcodeModule(std::move(Buff), Context, nullptr,
311 getLazyBitcodeModule(std::move(Buff), Context,
312312 /*ShouldLazyLoadMetadata*/ true);
313313 if (std::error_code EC = MOrErr.getError())
314314 return EC;
270270 /// Second step: for every call to an external function, try to import it.
271271
272272 // Linker that will be used for importing function
273 Linker TheLinker(DestModule, DiagnosticHandler);
273 Linker TheLinker(DestModule);
274274
275275 // Map of Module -> List of Function to import from the Module
276276 std::map>>
379379 auto ModuleLoader = [&M](StringRef Identifier) {
380380 return loadFile(Identifier, M.getContext());
381381 };
382 FunctionImporter Importer(*Index, diagnosticHandler, ModuleLoader);
382 FunctionImporter Importer(*Index, ModuleLoader);
383383 return Importer.importFunctions(M);
384384
385385 return false;
22 ;; drop-debug.bc was created from "void f(void) {}" with clang 3.5 and
33 ; -gline-tables-only, so it contains old debug info.
44
5 ; CHECK: warning: ignoring debug info with an invalid version (1) in {{.*}}/Inputs/drop-debug.bc
5 ; CHECK: WARNING: ignoring debug info with an invalid version (1) in {{.*}}/Inputs/drop-debug.bc
1414
1515 #include "BugDriver.h"
1616 #include "ToolRunner.h"
17 #include "llvm/IR/DiagnosticPrinter.h"
1817 #include "llvm/IR/Module.h"
1918 #include "llvm/IR/Verifier.h"
2019 #include "llvm/IRReader/IRReader.h"
112111 return Result;
113112 }
114113
115 static void diagnosticHandler(const DiagnosticInfo &DI) {
116 DiagnosticPrinterRawOStream DP(errs());
117 DI.print(DP);
118 errs() << '\n';
119 }
120
121114 // This method takes the specified list of LLVM input files, attempts to load
122115 // them, either as assembly or bitcode, then link them together. It returns
123116 // true on failure (if, for example, an input bitcode file could not be
138131 if (!M.get()) return true;
139132
140133 outs() << "Linking in input file: '" << Filenames[i] << "'\n";
141 if (Linker::linkModules(*Program, *M, diagnosticHandler))
134 if (Linker::linkModules(*Program, *M))
142135 return true;
143136 }
144137
1717 #include "llvm/Config/config.h" // for HAVE_LINK_R
1818 #include "llvm/IR/Constants.h"
1919 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
2120 #include "llvm/IR/Instructions.h"
2221 #include "llvm/IR/Module.h"
2322 #include "llvm/IR/Verifier.h"
210209 };
211210 }
212211
213 static void diagnosticHandler(const DiagnosticInfo &DI) {
214 DiagnosticPrinterRawOStream DP(errs());
215 DI.print(DP);
216 errs() << '\n';
217 if (DI.getSeverity() == DS_Error)
218 exit(1);
219 }
220
221212 /// Given two modules, link them together and run the program, checking to see
222213 /// if the program matches the diff. If there is an error, return NULL. If not,
223214 /// return the merged module. The Broken argument will be set to true if the
229220 std::unique_ptr M2,
230221 std::string &Error,
231222 bool &Broken) {
232 if (Linker::linkModules(*M1, *M2, diagnosticHandler))
223 if (Linker::linkModules(*M1, *M2))
233224 exit(1);
234225
235226 // Execute the program.
395386 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
396387 }
397388
398 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted,
399 diagnosticHandler))
389 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted))
400390 exit(1);
401391
402392 MiscompiledFunctions.clear();
423413 // extraction both didn't break the program, and didn't mask the problem.
424414 // Replace the current program with the loop extracted version, and try to
425415 // extract another loop.
426 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted,
427 diagnosticHandler))
416 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted))
428417 exit(1);
429418
430419 // All of the Function*'s in the MiscompiledFunctions list are in the old
592581 if (!I->isDeclaration())
593582 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
594583
595 if (Linker::linkModules(*ProgClone, *Extracted, diagnosticHandler))
584 if (Linker::linkModules(*ProgClone, *Extracted))
596585 exit(1);
597586
598587 // Set the new program and delete the old one.
878878 Context.setDiagnosticHandler(diagnosticHandlerForContext, nullptr, true);
879879
880880 std::unique_ptr Combined(new Module("ld-temp.o", Context));
881 IRMover L(*Combined, diagnosticHandler);
881 IRMover L(*Combined);
882882
883883 std::string DefaultTriple = sys::getDefaultTargetTriple();
884884
140140 errs() << '\n';
141141 }
142142
143 static void diagnosticHandlerWithContext(const DiagnosticInfo &DI, void *C) {
144 diagnosticHandler(DI);
145 }
146
143147 /// Import any functions requested via the -import option.
144148 static bool importFunctions(const char *argv0, LLVMContext &Context,
145149 Linker &L) {
264268 PrettyStackTraceProgram X(argc, argv);
265269
266270 LLVMContext &Context = getGlobalContext();
271 Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
272
267273 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
268274 cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
269275
270276 auto Composite = make_unique("llvm-link", Context);
271 Linker L(*Composite, diagnosticHandler);
277 Linker L(*Composite);
272278
273279 unsigned Flags = Linker::Flags::None;
274280 if (Internalize)
7070 BasicBlock *ExitBB;
7171 };
7272
73 static void expectNoDiags(const DiagnosticInfo &DI) { EXPECT_TRUE(false); }
73 static void expectNoDiags(const DiagnosticInfo &DI, void *C) {
74 EXPECT_TRUE(false);
75 }
7476
7577 TEST_F(LinkModuleTest, BlockAddress) {
7678 IRBuilder<> Builder(EntryBB);
9496 Builder.CreateRet(ConstantPointerNull::get(Type::getInt8PtrTy(Ctx)));
9597
9698 Module *LinkedModule = new Module("MyModuleLinked", Ctx);
97 Linker::linkModules(*LinkedModule, *M, expectNoDiags);
99 Ctx.setDiagnosticHandler(expectNoDiags);
100 Linker::linkModules(*LinkedModule, *M);
98101
99102 // Delete the original module.
100103 M.reset();
170173 TEST_F(LinkModuleTest, EmptyModule) {
171174 std::unique_ptr InternalM(getInternal(Ctx));
172175 std::unique_ptr EmptyM(new Module("EmptyModule1", Ctx));
173 Linker::linkModules(*EmptyM, *InternalM, expectNoDiags);
176 Ctx.setDiagnosticHandler(expectNoDiags);
177 Linker::linkModules(*EmptyM, *InternalM);
174178 }
175179
176180 TEST_F(LinkModuleTest, EmptyModule2) {
177181 std::unique_ptr InternalM(getInternal(Ctx));
178182 std::unique_ptr EmptyM(new Module("EmptyModule1", Ctx));
179 Linker::linkModules(*InternalM, *EmptyM, expectNoDiags);
183 Ctx.setDiagnosticHandler(expectNoDiags);
184 Linker::linkModules(*InternalM, *EmptyM);
180185 }
181186
182187 TEST_F(LinkModuleTest, TypeMerge) {
191196 "@t2 = weak global %t zeroinitializer\n";
192197 std::unique_ptr M2 = parseAssemblyString(M2Str, Err, C);
193198
194 Linker::linkModules(*M1, *M2, [](const llvm::DiagnosticInfo &) {});
199 Ctx.setDiagnosticHandler(expectNoDiags);
200 Linker::linkModules(*M1, *M2);
195201
196202 EXPECT_EQ(M1->getNamedGlobal("t1")->getType(),
197203 M1->getNamedGlobal("t2")->getType());
268274 // Link into destination module.
269275 auto Dst = llvm::make_unique("Linked", C);
270276 ASSERT_TRUE(Dst.get());
271 Linker::linkModules(*Dst, *Src, [](const llvm::DiagnosticInfo &) {});
277 Ctx.setDiagnosticHandler(expectNoDiags);
278 Linker::linkModules(*Dst, *Src);
272279
273280 // Check that distinct metadata was moved, not cloned. Even !4, the uniqued
274281 // node, should effectively be moved, since its only operand hasn't changed.