llvm.org GIT mirror llvm / c8a1169
IR: Add COMDATs to the IR This new IR facility allows us to represent the object-file semantic of a COMDAT group. COMDATs allow us to tie together sections and make the inclusion of one dependent on another. This is required to implement features like MS ABI VFTables and optimizing away certain kinds of initialization in C++. This functionality is only representable in COFF and ELF, Mach-O has no similar mechanism. Differential Revision: http://reviews.llvm.org/D4178 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@211920 91177308-0d34-0410-b5e6-96231b3b80d8 David Majnemer 5 years ago
56 changed file(s) with 1513 addition(s) and 106 deletion(s). Raw diff Collapse all Expand all
561561
562562 LLVM allows an explicit section to be specified for globals. If the
563563 target supports it, it will emit globals to the section specified.
564 Additionally, the global can placed in a comdat if the target has the necessary
565 support.
564566
565567 By default, global initializers are optimized by assuming that global
566568 variables defined within the module are not modified from their
626628 :ref:`parameter attribute ` for the return type, a function
627629 name, a (possibly empty) argument list (each with optional :ref:`parameter
628630 attributes `), optional :ref:`function attributes `,
629 an optional section, an optional alignment, an optional :ref:`garbage
630 collector name `, an optional :ref:`prefix `, an opening
631 an optional section, an optional alignment,
632 an optional :ref:`comdat `,
633 an optional :ref:`garbage collector name `, an optional :ref:`prefix `, an opening
631634 curly brace, a list of basic blocks, and a closing curly brace.
632635
633636 LLVM function declarations consist of the "``declare``" keyword, an
657660
658661 LLVM allows an explicit section to be specified for functions. If the
659662 target supports it, it will emit functions to the section specified.
663 Additionally, the function can placed in a COMDAT.
660664
661665 An explicit alignment may be specified for a function. If not present,
662666 or if the alignment is set to zero, the alignment of the function is set
672676 define [linkage] [visibility] [DLLStorageClass]
673677 [cconv] [ret attrs]
674678 @ ([argument list])
675 [unnamed_addr] [fn Attrs] [section "name"] [align N]
676 [gc] [prefix Constant] { ... }
679 [unnamed_addr] [fn Attrs] [section "name"] [comdat $]
680 [align N] [gc] [prefix Constant] { ... }
677681
678682 .. _langref_aliases:
679683
714718
715719 * No global value in the expression can be a declaration, since that
716720 would require a relocation, which is not possible.
721
722 .. _langref_comdats:
723
724 Comdats
725 -------
726
727 Comdat IR provides access to COFF and ELF object file COMDAT functionality.
728
729 Comdats have a name which represents the COMDAT key. All global objects which
730 specify this key will only end up in the final object file if the linker chooses
731 that key over some other key. Aliases are placed in the same COMDAT that their
732 aliasee computes to, if any.
733
734 Comdats have a selection kind to provide input on how the linker should
735 choose between keys in two different object files.
736
737 Syntax::
738
739 $ = comdat SelectionKind
740
741 The selection kind must be one of the following:
742
743 ``any``
744 The linker may choose any COMDAT key, the choice is arbitrary.
745 ``exactmatch``
746 The linker may choose any COMDAT key but the sections must contain the
747 same data.
748 ``largest``
749 The linker will choose the section containing the largest COMDAT key.
750 ``noduplicates``
751 The linker requires that only section with this COMDAT key exist.
752 ``samesize``
753 The linker may choose any COMDAT key but the sections must contain the
754 same amount of data.
755
756 Note that the Mach-O platform doesn't support COMDATs and ELF only supports
757 ``any`` as a selection kind.
758
759 Here is an example of a COMDAT group where a function will only be selected if
760 the COMDAT key's section is the largest:
761
762 .. code-block:: llvm
763
764 $foo = comdat largest
765 @foo = global i32 2, comdat $foo
766
767 define void @bar() comdat $foo {
768 ret void
769 }
770
771 In a COFF object file, this will create a COMDAT section with selection kind
772 ``IMAGE_COMDAT_SELECT_LARGEST`` containing the contents of the ``@foo`` symbol
773 and another COMDAT section with selection kind
774 ``IMAGE_COMDAT_SELECT_ASSOCIATIVE`` which is associated with the first COMDAT
775 section and contains the contents of the ``@baz`` symbol.
776
777 There are some restrictions on the properties of the global object.
778 It, or an alias to it, must have the same name as the COMDAT group when
779 targeting COFF.
780 The contents and size of this object may be used during link-time to determine
781 which COMDAT groups get selected depending on the selection kind.
782 Because the name of the object must match the name of the COMDAT group, the
783 linkage of the global object must not be local; local symbols can get renamed
784 if a collision occurs in the symbol table.
785
786 The combined use of COMDATS and section attributes may yield surprising results.
787 For example:
788
789 .. code-block:: llvm
790
791 $foo = comdat any
792 $bar = comdat any
793 @g1 = global i32 42, section "sec", comdat $foo
794 @g2 = global i32 42, section "sec", comdat $bar
795
796 From the object file perspective, this requires the creation of two sections
797 with the same name. This is necessary because both globals belong to different
798 COMDAT groups and COMDATs, at the object file level, are represented by
799 sections.
800
801 Note that certain IR constructs like global variables and functions may create
802 COMDATs in the object file in addition to any which are specified using COMDAT
803 IR. This arises, for example, when a global variable has linkonce_odr linkage.
717804
718805 .. _namedmetadatastructure:
719806
2121 /// class should have an implementation of operator== and of operator<.
2222 /// Entries can be fetched using operator[] with the entry ID.
2323 template class UniqueVector {
24 public:
25 typedef typename std::vector VectorType;
26 typedef typename VectorType::iterator iterator;
27 typedef typename VectorType::const_iterator const_iterator;
28
2429 private:
2530 // Map - Used to handle the correspondence of entry to ID.
2631 std::map Map;
2732
2833 // Vector - ID ordered vector of entries. Entries can be indexed by ID - 1.
2934 //
30 std::vector Vector;
35 VectorType Vector;
3136
3237 public:
3338 /// insert - Append entry to the vector if it doesn't already exist. Returns
6772 return Vector[ID - 1];
6873 }
6974
75 /// \brief Return an iterator to the start of the vector.
76 iterator begin() { return Vector.begin(); }
77
78 /// \brief Return an iterator to the start of the vector.
79 const_iterator begin() const { return Vector.begin(); }
80
81 /// \brief Return an iterator to the end of the vector.
82 iterator end() { return Vector.end(); }
83
84 /// \brief Return an iterator to the end of the vector.
85 const_iterator end() const { return Vector.end(); }
86
7087 /// size - Returns the number of entries in the vector.
7188 ///
7289 size_t size() const { return Vector.size(); }
7070 // MODULE_CODE_PURGEVALS: [numvals]
7171 MODULE_CODE_PURGEVALS = 10,
7272
73 MODULE_CODE_GCNAME = 11 // GCNAME: [strchr x N]
73 MODULE_CODE_GCNAME = 11, // GCNAME: [strchr x N]
74 MODULE_CODE_COMDAT = 12, // COMDAT: [selection_kind, name]
7475 };
7576
7677 /// PARAMATTR blocks have code for defining a parameter attribute set.
375376 ATTR_KIND_JUMP_TABLE = 40
376377 };
377378
379 enum ComdatSelectionKindCodes {
380 COMDAT_SELECTION_KIND_ANY = 1,
381 COMDAT_SELECTION_KIND_EXACT_MATCH = 2,
382 COMDAT_SELECTION_KIND_LARGEST = 3,
383 COMDAT_SELECTION_KIND_NO_DUPLICATES = 4,
384 COMDAT_SELECTION_KIND_SAME_SIZE = 5,
385 };
386
378387 } // End bitc namespace
379388 } // End llvm namespace
380389
0 //===-- llvm/IR/Comdat.h - Comdat definitions -------------------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// @file
10 /// This file contains the declaration of the Comdat class, which represents a
11 /// single COMDAT in LLVM.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_IR_COMDAT_H
16 #define LLVM_IR_COMDAT_H
17
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Support/Compiler.h"
20
21 namespace llvm {
22
23 class raw_ostream;
24 template class StringMapEntry;
25
26 // This is a Name X SelectionKind pair. The reason for having this be an
27 // independent object instead of just adding the name and the SelectionKind
28 // to a GlobalObject is that it is invalid to have two Comdats with the same
29 // name but different SelectionKind. This structure makes that unrepresentable.
30 class Comdat {
31 public:
32 enum SelectionKind {
33 Any, ///< The linker may choose any COMDAT.
34 ExactMatch, ///< The data referenced by the COMDAT must be the same.
35 Largest, ///< The linker will choose the largest COMDAT.
36 NoDuplicates, ///< No other Module may specify this COMDAT.
37 SameSize, ///< The data referenced by the COMDAT must be the same size.
38 };
39
40 Comdat(Comdat &&C);
41 SelectionKind getSelectionKind() const { return SK; }
42 void setSelectionKind(SelectionKind Val) { SK = Val; }
43 StringRef getName() const;
44 void print(raw_ostream &OS) const;
45 void dump() const;
46
47 private:
48 friend class Module;
49 Comdat();
50 Comdat(SelectionKind SK, StringMapEntry *Name);
51 Comdat(const Comdat &) LLVM_DELETED_FUNCTION;
52
53 // Points to the map in Module.
54 StringMapEntry *Name;
55 SelectionKind SK;
56 };
57
58 inline raw_ostream &operator<<(raw_ostream &OS, const Comdat &C) {
59 C.print(OS);
60 return OS;
61 }
62
63 } // end llvm namespace
64
65 #endif
8686 return getOperand(0);
8787 }
8888
89 const GlobalObject *getBaseObject() const {
90 return const_cast(this)->getBaseObject();
91 }
92 GlobalObject *getBaseObject() {
93 return dyn_cast(getAliasee()->stripInBoundsOffsets());
94 }
95
96 const GlobalObject *getBaseObject(const DataLayout &DL, APInt &Offset) const {
97 return const_cast(this)->getBaseObject(DL, Offset);
98 }
99 GlobalObject *getBaseObject(const DataLayout &DL, APInt &Offset) {
100 return dyn_cast(
101 getAliasee()->stripAndAccumulateInBoundsConstantOffsets(DL, Offset));
102 }
103
89104 static bool isValidLinkage(LinkageTypes L) {
90105 return isExternalLinkage(L) || isLocalLinkage(L) ||
91106 isWeakLinkage(L) || isLinkOnceLinkage(L);
1919 #include "llvm/IR/GlobalValue.h"
2020
2121 namespace llvm {
22
22 class Comdat;
2323 class Module;
2424
2525 class GlobalObject : public GlobalValue {
2828 protected:
2929 GlobalObject(Type *Ty, ValueTy VTy, Use *Ops, unsigned NumOps,
3030 LinkageTypes Linkage, const Twine &Name)
31 : GlobalValue(Ty, VTy, Ops, NumOps, Linkage, Name) {
31 : GlobalValue(Ty, VTy, Ops, NumOps, Linkage, Name), ObjComdat(nullptr) {
3232 setGlobalValueSubClassData(0);
3333 }
3434
3535 std::string Section; // Section to emit this into, empty means default
36 Comdat *ObjComdat;
3637 public:
3738 unsigned getAlignment() const {
3839 return (1u << getGlobalValueSubClassData()) >> 1;
4243 bool hasSection() const { return !StringRef(getSection()).empty(); }
4344 const char *getSection() const { return Section.c_str(); }
4445 void setSection(StringRef S);
46
47 bool hasComdat() const { return getComdat() != nullptr; }
48 const Comdat *getComdat() const { return ObjComdat; }
49 Comdat *getComdat() { return ObjComdat; }
50 void setComdat(Comdat *C) { ObjComdat = C; }
4551
4652 void copyAttributesFrom(const GlobalValue *Src) override;
4753
2222
2323 namespace llvm {
2424
25 class Comdat;
2526 class PointerType;
2627 class Module;
2728
109110 bool hasUnnamedAddr() const { return UnnamedAddr; }
110111 void setUnnamedAddr(bool Val) { UnnamedAddr = Val; }
111112
113 bool hasComdat() const { return getComdat() != nullptr; }
114 Comdat *getComdat();
115 const Comdat *getComdat() const {
116 return const_cast(this)->getComdat();
117 }
118
112119 VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
113120 bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
114121 bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
1515 #define LLVM_IR_MODULE_H
1616
1717 #include "llvm/ADT/iterator_range.h"
18 #include "llvm/IR/Comdat.h"
1819 #include "llvm/IR/DataLayout.h"
1920 #include "llvm/IR/Function.h"
2021 #include "llvm/IR/GlobalAlias.h"
122123 typedef iplist AliasListType;
123124 /// The type for the list of named metadata.
124125 typedef ilist NamedMDListType;
126 /// The type of the comdat "symbol" table.
127 typedef StringMap ComdatSymTabType;
125128
126129 /// The Global Variable iterator.
127130 typedef GlobalListType::iterator global_iterator;
196199 NamedMDListType NamedMDList; ///< The named metadata in the module
197200 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
198201 ValueSymbolTable *ValSymTab; ///< Symbol table for values
202 ComdatSymTabType ComdatSymTab; ///< Symbol table for COMDATs
199203 std::unique_ptr
200204 Materializer; ///< Used to materialize GlobalValues
201205 std::string ModuleID; ///< Human readable identifier for the module
403407 void eraseNamedMetadata(NamedMDNode *NMD);
404408
405409 /// @}
410 /// @name Comdat Accessors
411 /// @{
412
413 /// Return the Comdat in the module with the specified name. It is created
414 /// if it didn't already exist.
415 Comdat *getOrInsertComdat(StringRef Name);
416
417 /// @}
406418 /// @name Module Flags Accessors
407419 /// @{
408420
503515 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
504516 /// Get the Module's symbol table of global variable and function identifiers.
505517 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
518 /// Get the Module's symbol table for COMDATs (constant).
519 const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
520 /// Get the Module's symbol table for COMDATs.
521 ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
506522
507523 /// @}
508524 /// @name Global Variable Iteration
1414
1515 namespace llvm {
1616
17 class Comdat;
18 class GlobalValue;
1719 class Module;
1820 class StringRef;
1921 class StructType;
208208 return LexToken();
209209 case '+': return LexPositive();
210210 case '@': return LexAt();
211 case '$': return LexDollar();
211212 case '%': return LexPercent();
212213 case '"': return LexQuote();
213214 case '.':
219220 if (CurPtr[0] == '.' && CurPtr[1] == '.') {
220221 CurPtr += 2;
221222 return lltok::dotdotdot;
222 }
223 return lltok::Error;
224 case '$':
225 if (const char *Ptr = isLabelTail(CurPtr)) {
226 CurPtr = Ptr;
227 StrVal.assign(TokStart, CurPtr-1);
228 return lltok::LabelStr;
229223 }
230224 return lltok::Error;
231225 case ';':
302296 UIntVal = unsigned(Val);
303297 return lltok::GlobalID;
304298 }
299
300 return lltok::Error;
301 }
302
303 lltok::Kind LLLexer::LexDollar() {
304 if (const char *Ptr = isLabelTail(TokStart)) {
305 CurPtr = Ptr;
306 StrVal.assign(TokStart, CurPtr - 1);
307 return lltok::LabelStr;
308 }
309
310 // Handle DollarStringConstant: $\"[^\"]*\"
311 if (CurPtr[0] == '"') {
312 ++CurPtr;
313
314 while (1) {
315 int CurChar = getNextChar();
316
317 if (CurChar == EOF) {
318 Error("end of file in COMDAT variable name");
319 return lltok::Error;
320 }
321 if (CurChar == '"') {
322 StrVal.assign(TokStart + 2, CurPtr - 1);
323 UnEscapeLexed(StrVal);
324 if (StringRef(StrVal).find_first_of(0) != StringRef::npos) {
325 Error("Null bytes are not allowed in names");
326 return lltok::Error;
327 }
328 return lltok::ComdatVar;
329 }
330 }
331 }
332
333 // Handle ComdatVarName: $[-a-zA-Z$._][-a-zA-Z$._0-9]*
334 if (ReadVarName())
335 return lltok::ComdatVar;
305336
306337 return lltok::Error;
307338 }
617648 KEYWORD(type);
618649 KEYWORD(opaque);
619650
651 KEYWORD(comdat);
652
653 // Comdat types
654 KEYWORD(any);
655 KEYWORD(exactmatch);
656 KEYWORD(largest);
657 KEYWORD(noduplicates);
658 KEYWORD(samesize);
659
620660 KEYWORD(eq); KEYWORD(ne); KEYWORD(slt); KEYWORD(sgt); KEYWORD(sle);
621661 KEYWORD(sge); KEYWORD(ult); KEYWORD(ugt); KEYWORD(ule); KEYWORD(uge);
622662 KEYWORD(oeq); KEYWORD(one); KEYWORD(olt); KEYWORD(ogt); KEYWORD(ole);
8080 lltok::Kind LexDigitOrNegative();
8181 lltok::Kind LexPositive();
8282 lltok::Kind LexAt();
83 lltok::Kind LexDollar();
8384 lltok::Kind LexExclaim();
8485 lltok::Kind LexPercent();
8586 lltok::Kind LexQuote();
162162 return Error(I->second.second,
163163 "use of undefined type named '" + I->getKey() + "'");
164164
165 if (!ForwardRefComdats.empty())
166 return Error(ForwardRefComdats.begin()->second,
167 "use of undefined comdat '$" +
168 ForwardRefComdats.begin()->first + "'");
169
165170 if (!ForwardRefVals.empty())
166171 return Error(ForwardRefVals.begin()->second.second,
167172 "use of undefined value '@" + ForwardRefVals.begin()->first +
237242 case lltok::LocalVar: if (ParseNamedType()) return true; break;
238243 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
239244 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
245 case lltok::ComdatVar: if (parseComdat()) return true; break;
240246 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
241247 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
242248
512518 UnnamedAddr);
513519 }
514520
521 bool LLParser::parseComdat() {
522 assert(Lex.getKind() == lltok::ComdatVar);
523 std::string Name = Lex.getStrVal();
524 LocTy NameLoc = Lex.getLoc();
525 Lex.Lex();
526
527 if (ParseToken(lltok::equal, "expected '=' here"))
528 return true;
529
530 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
531 return TokError("expected comdat type");
532
533 Comdat::SelectionKind SK;
534 switch (Lex.getKind()) {
535 default:
536 return TokError("unknown selection kind");
537 case lltok::kw_any:
538 SK = Comdat::Any;
539 break;
540 case lltok::kw_exactmatch:
541 SK = Comdat::ExactMatch;
542 break;
543 case lltok::kw_largest:
544 SK = Comdat::Largest;
545 break;
546 case lltok::kw_noduplicates:
547 SK = Comdat::NoDuplicates;
548 break;
549 case lltok::kw_samesize:
550 SK = Comdat::SameSize;
551 break;
552 }
553 Lex.Lex();
554
555 // See if the comdat was forward referenced, if so, use the comdat.
556 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
557 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
558 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
559 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
560
561 Comdat *C;
562 if (I != ComdatSymTab.end())
563 C = &I->second;
564 else
565 C = M->getOrInsertComdat(Name);
566 C->setSelectionKind(SK);
567
568 return false;
569 }
570
515571 // MDString:
516572 // ::= '!' STRINGCONSTANT
517573 bool LLParser::ParseMDString(MDString *&Result) {
837893 if (ParseOptionalAlignment(Alignment)) return true;
838894 GV->setAlignment(Alignment);
839895 } else {
840 TokError("unknown global variable property!");
896 Comdat *C;
897 if (parseOptionalComdat(C))
898 return true;
899 if (C)
900 GV->setComdat(C);
901 else
902 return TokError("unknown global variable property!");
841903 }
842904 }
843905
10921154
10931155 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
10941156 return FwdVal;
1157 }
1158
1159
1160 //===----------------------------------------------------------------------===//
1161 // Comdat Reference/Resolution Routines.
1162 //===----------------------------------------------------------------------===//
1163
1164 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1165 // Look this name up in the comdat symbol table.
1166 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1167 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1168 if (I != ComdatSymTab.end())
1169 return &I->second;
1170
1171 // Otherwise, create a new forward reference for this value and remember it.
1172 Comdat *C = M->getOrInsertComdat(Name);
1173 ForwardRefComdats[Name] = Loc;
1174 return C;
10951175 }
10961176
10971177
27892869 ParseGlobalValue(Ty, V);
27902870 }
27912871
2872 bool LLParser::parseOptionalComdat(Comdat *&C) {
2873 C = nullptr;
2874 if (!EatIfPresent(lltok::kw_comdat))
2875 return false;
2876 if (Lex.getKind() != lltok::ComdatVar)
2877 return TokError("expected comdat variable");
2878 LocTy Loc = Lex.getLoc();
2879 StringRef Name = Lex.getStrVal();
2880 C = getComdat(Name, Loc);
2881 Lex.Lex();
2882 return false;
2883 }
2884
27922885 /// ParseGlobalValueVector
27932886 /// ::= /*empty*/
27942887 /// ::= TypeAndValue (',' TypeAndValue)*
30893182 bool UnnamedAddr;
30903183 LocTy UnnamedAddrLoc;
30913184 Constant *Prefix = nullptr;
3185 Comdat *C;
30923186
30933187 if (ParseArgumentList(ArgList, isVarArg) ||
30943188 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
30973191 BuiltinLoc) ||
30983192 (EatIfPresent(lltok::kw_section) &&
30993193 ParseStringConstant(Section)) ||
3194 parseOptionalComdat(C) ||
31003195 ParseOptionalAlignment(Alignment) ||
31013196 (EatIfPresent(lltok::kw_gc) &&
31023197 ParseStringConstant(GC)) ||
31993294 Fn->setUnnamedAddr(UnnamedAddr);
32003295 Fn->setAlignment(Alignment);
32013296 Fn->setSection(Section);
3297 Fn->setComdat(C);
32023298 if (!GC.empty()) Fn->setGC(GC.c_str());
32033299 Fn->setPrefixData(Prefix);
32043300 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3333 class Instruction;
3434 class Constant;
3535 class GlobalValue;
36 class Comdat;
3637 class MDString;
3738 class MDNode;
3839 class StructType;
121122 std::map > ForwardRefValIDs;
122123 std::vector NumberedVals;
123124
125 // Comdat forward reference information.
126 std::map ForwardRefComdats;
127
124128 // References to blockaddress. The key is the function ValID, the value is
125129 // a list of references to blocks in that function.
126130 std::map > >
152156 /// exists but does not have the right type.
153157 GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
154158 GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
159
160 /// Get a Comdat with the specified name, creating a forward reference
161 /// record if needed.
162 Comdat *getComdat(const std::string &N, LocTy Loc);
155163
156164 // Helper Routines.
157165 bool ParseToken(lltok::Kind T, const char *ErrMsg);
246254 bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Visibility,
247255 unsigned DLLStorageClass,
248256 GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
257 bool parseComdat();
249258 bool ParseStandaloneMetadata();
250259 bool ParseNamedMetadata();
251260 bool ParseMDString(MDString *&Result);
357366 bool ParseGlobalValue(Type *Ty, Constant *&V);
358367 bool ParseGlobalTypeAndValue(Constant *&V);
359368 bool ParseGlobalValueVector(SmallVectorImpl &Elts);
369 bool parseOptionalComdat(Comdat *&C);
360370 bool ParseMetadataListValue(ValID &ID, PerFunctionState *PFS);
361371 bool ParseMetadataValue(ValID &ID, PerFunctionState *PFS);
362372 bool ParseMDNodeVector(SmallVectorImpl &, PerFunctionState *PFS);
141141 kw_type,
142142 kw_opaque,
143143
144 kw_comdat,
145
146 // Comdat types
147 kw_any,
148 kw_exactmatch,
149 kw_largest,
150 kw_noduplicates,
151 kw_samesize,
152
144153 kw_eq, kw_ne, kw_slt, kw_sgt, kw_sle, kw_sge, kw_ult, kw_ugt, kw_ule,
145154 kw_uge, kw_oeq, kw_one, kw_olt, kw_ogt, kw_ole, kw_oge, kw_ord, kw_uno,
146155 kw_ueq, kw_une,
179188 // String valued tokens (StrVal).
180189 LabelStr, // foo:
181190 GlobalVar, // @foo @"foo"
191 ComdatVar, // $foo
182192 LocalVar, // %foo %"foo"
183193 MetadataVar, // !foo
184194 StringConstant, // "foo"
4242 std::vector().swap(TypeList);
4343 ValueList.clear();
4444 MDValueList.clear();
45 std::vector().swap(ComdatList);
4546
4647 std::vector().swap(MAttributes);
4748 std::vector().swap(FunctionBBs);
199200 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
200201 default: // Map unknown scopes to cross-thread.
201202 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
203 }
204 }
205
206 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
207 switch (Val) {
208 default: // Map unknown selection kinds to any.
209 case bitc::COMDAT_SELECTION_KIND_ANY:
210 return Comdat::Any;
211 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
212 return Comdat::ExactMatch;
213 case bitc::COMDAT_SELECTION_KIND_LARGEST:
214 return Comdat::Largest;
215 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
216 return Comdat::NoDuplicates;
217 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
218 return Comdat::SameSize;
202219 }
203220 }
204221
18371854 GCTable.push_back(S);
18381855 break;
18391856 }
1857 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1858 if (Record.size() < 2)
1859 return Error(InvalidRecord);
1860 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1861 unsigned ComdatNameSize = Record[1];
1862 std::string ComdatName;
1863 ComdatName.reserve(ComdatNameSize);
1864 for (unsigned i = 0; i != ComdatNameSize; ++i)
1865 ComdatName += (char)Record[2 + i];
1866 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1867 C->setSelectionKind(SK);
1868 ComdatList.push_back(C);
1869 break;
1870 }
18401871 // GLOBALVAR: [pointer type, isconst, initid,
18411872 // linkage, alignment, section, visibility, threadlocal,
18421873 // unnamed_addr, dllstorageclass]
18971928 // Remember which value to use for the global initializer.
18981929 if (unsigned InitID = Record[2])
18991930 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1931
1932 if (Record.size() > 11)
1933 if (unsigned ComdatID = Record[11]) {
1934 assert(ComdatID <= ComdatList.size());
1935 NewGV->setComdat(ComdatList[ComdatID - 1]);
1936 }
19001937 break;
19011938 }
19021939 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
19491986 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
19501987 else
19511988 UpgradeDLLImportExportLinkage(Func, Record[3]);
1989
1990 if (Record.size() > 12)
1991 if (unsigned ComdatID = Record[12]) {
1992 assert(ComdatID <= ComdatList.size());
1993 Func->setComdat(ComdatList[ComdatID - 1]);
1994 }
19521995
19531996 ValueList.push_back(Func);
19541997
2525 #include
2626
2727 namespace llvm {
28 class Comdat;
2829 class MemoryBuffer;
2930 class LLVMContext;
3031
134135 std::vector TypeList;
135136 BitcodeReaderValueList ValueList;
136137 BitcodeReaderMDValueList MDValueList;
138 std::vector ComdatList;
137139 SmallVector InstructionList;
138140 SmallVector, 64> UseListRecords;
139141
523523 llvm_unreachable("Invalid TLS model");
524524 }
525525
526 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
527 switch (C.getSelectionKind()) {
528 case Comdat::Any:
529 return bitc::COMDAT_SELECTION_KIND_ANY;
530 case Comdat::ExactMatch:
531 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
532 case Comdat::Largest:
533 return bitc::COMDAT_SELECTION_KIND_LARGEST;
534 case Comdat::NoDuplicates:
535 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
536 case Comdat::SameSize:
537 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
538 }
539 llvm_unreachable("Invalid selection kind");
540 }
541
542 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
543 SmallVector Vals;
544 for (const Comdat *C : VE.getComdats()) {
545 // COMDAT: [selection_kind, name]
546 Vals.push_back(getEncodedComdatSelectionKind(*C));
547 Vals.push_back(C->getName().size());
548 for (char Chr : C->getName())
549 Vals.push_back((unsigned char)Chr);
550 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
551 Vals.clear();
552 }
553 }
554
526555 // Emit top-level description of module, including target triple, inline asm,
527556 // descriptors for global variables, and function prototype info.
528557 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
624653 if (GV.isThreadLocal() ||
625654 GV.getVisibility() != GlobalValue::DefaultVisibility ||
626655 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
627 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass) {
656 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
657 GV.hasComdat()) {
628658 Vals.push_back(getEncodedVisibility(GV));
629659 Vals.push_back(getEncodedThreadLocalMode(GV));
630660 Vals.push_back(GV.hasUnnamedAddr());
631661 Vals.push_back(GV.isExternallyInitialized());
632662 Vals.push_back(getEncodedDLLStorageClass(GV));
663 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
633664 } else {
634665 AbbrevToUse = SimpleGVarAbbrev;
635666 }
655686 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
656687 : 0);
657688 Vals.push_back(getEncodedDLLStorageClass(F));
689 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
658690
659691 unsigned AbbrevToUse = 0;
660692 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
19141946 // Emit information describing all of the types in the module.
19151947 WriteTypeTable(VE, Stream);
19161948
1949 writeComdats(VE, Stream);
1950
19171951 // Emit top-level description of module, including target triple, inline asm,
19181952 // descriptors for global variables, and function prototype info.
19191953 WriteModuleInfo(M, VE, Stream);
116116 return I->second;
117117 }
118118
119 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
120 unsigned ComdatID = Comdats.idFor(C);
121 assert(ComdatID && "Comdat not found!");
122 return ComdatID;
123 }
124
119125 void ValueEnumerator::setInstructionID(const Instruction *I) {
120126 InstructionMap[I] = InstructionCount++;
121127 }
306312 return;
307313 }
308314
315 if (auto *GO = dyn_cast(V))
316 if (const Comdat *C = GO->getComdat())
317 Comdats.insert(C);
318
309319 // Enumerate the type of this value.
310320 EnumerateType(V->getType());
311321
1515
1616 #include "llvm/ADT/DenseMap.h"
1717 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/UniqueVector.h"
1819 #include "llvm/IR/Attributes.h"
1920 #include
2021
2425 class Value;
2526 class Instruction;
2627 class BasicBlock;
28 class Comdat;
2729 class Function;
2830 class Module;
2931 class MDNode;
4749 typedef DenseMap ValueMapType;
4850 ValueMapType ValueMap;
4951 ValueList Values;
52
53 typedef UniqueVector ComdatSetType;
54 ComdatSetType Comdats;
55
5056 ValueList MDValues;
5157 SmallVector FunctionLocalMDs;
5258 ValueMapType MDValueMap;
138144 return AttributeGroups;
139145 }
140146
147 const ComdatSetType &getComdats() const { return Comdats; }
148 unsigned getComdatID(const Comdat *C) const;
149
141150 /// getGlobalBasicBlockID - This returns the function-specific ID for the
142151 /// specified basic block. This is relatively expensive information, so it
143152 /// should only be used by rare constructs such as address-of-label.
191191 return Flags;
192192 }
193193
194 static const Comdat *getELFComdat(const GlobalValue *GV) {
195 const Comdat *C = GV->getComdat();
196 if (!C)
197 return nullptr;
198
199 if (C->getSelectionKind() != Comdat::Any)
200 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
201 C->getName() + "' cannot be lowered.");
202
203 return C;
204 }
205
194206 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
195207 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
196208 const TargetMachine &TM) const {
199211 // Infer section flags from the section name if we can.
200212 Kind = getELFKindForNamedSection(SectionName, Kind);
201213
214 StringRef Group = "";
215 unsigned Flags = getELFSectionFlags(Kind);
216 if (const Comdat *C = getELFComdat(GV)) {
217 Group = C->getName();
218 Flags |= ELF::SHF_GROUP;
219 }
202220 return getContext().getELFSection(SectionName,
203 getELFSectionType(SectionName, Kind),
204 getELFSectionFlags(Kind), Kind);
221 getELFSectionType(SectionName, Kind), Flags,
222 Kind, /*EntrySize=*/0, Group);
205223 }
206224
207225 /// getSectionPrefixForGlobal - Return the section prefix name used by options
222240 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
223241 return ".data.rel.ro.";
224242 }
225
226243
227244 const MCSection *TargetLoweringObjectFileELF::
228245 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
237254
238255 // If this global is linkonce/weak and the target handles this by emitting it
239256 // into a 'uniqued' section name, create and return the section now.
240 if ((GV->isWeakForLinker() || EmitUniquedSection) &&
257 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
241258 !Kind.isCommon()) {
242259 StringRef Prefix = getSectionPrefixForGlobal(Kind);
243260
246263
247264 StringRef Group = "";
248265 unsigned Flags = getELFSectionFlags(Kind);
249 if (GV->isWeakForLinker()) {
250 Group = Name.substr(Prefix.size());
266 if (GV->isWeakForLinker() || GV->hasComdat()) {
267 if (const Comdat *C = getELFComdat(GV))
268 Group = C->getName();
269 else
270 Group = Name.substr(Prefix.size());
251271 Flags |= ELF::SHF_GROUP;
252272 }
253273
481501 Streamer.AddBlankLine();
482502 }
483503
504 static void checkMachOComdat(const GlobalValue *GV) {
505 const Comdat *C = GV->getComdat();
506 if (!C)
507 return;
508
509 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
510 "' cannot be lowered.");
511 }
512
484513 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
485514 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
486515 const TargetMachine &TM) const {
488517 StringRef Segment, Section;
489518 unsigned TAA = 0, StubSize = 0;
490519 bool TAAParsed;
520
521 checkMachOComdat(GV);
522
491523 std::string ErrorCode =
492524 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
493525 TAA, TAAParsed, StubSize);
558590 const MCSection *TargetLoweringObjectFileMachO::
559591 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
560592 Mangler &Mang, const TargetMachine &TM) const {
593 checkMachOComdat(GV);
561594
562595 // Handle thread local data.
563596 if (Kind.isThreadBSS()) return TLSBSSSection;
726759 return Flags;
727760 }
728761
762 const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
763 const Comdat *C = GV->getComdat();
764 assert(C && "expected GV to have a Comdat!");
765
766 StringRef ComdatGVName = C->getName();
767 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
768 if (!ComdatGV)
769 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
770 "' does not exist.");
771
772 if (ComdatGV->getComdat() != C)
773 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
774 "' is not a key for it's COMDAT.");
775
776 return ComdatGV;
777 }
778
779 static int getSelectionForCOFF(const GlobalValue *GV) {
780 if (const Comdat *C = GV->getComdat()) {
781 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
782 if (const auto *GA = dyn_cast(ComdatKey))
783 ComdatKey = GA->getBaseObject();
784 if (ComdatKey == GV) {
785 switch (C->getSelectionKind()) {
786 case Comdat::Any:
787 return COFF::IMAGE_COMDAT_SELECT_ANY;
788 case Comdat::ExactMatch:
789 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
790 case Comdat::Largest:
791 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
792 case Comdat::NoDuplicates:
793 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
794 case Comdat::SameSize:
795 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
796 }
797 } else {
798 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
799 }
800 } else if (GV->isWeakForLinker()) {
801 return COFF::IMAGE_COMDAT_SELECT_ANY;
802 }
803 return 0;
804 }
805
729806 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
730807 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
731808 const TargetMachine &TM) const {
733810 unsigned Characteristics = getCOFFSectionFlags(Kind);
734811 StringRef Name = GV->getSection();
735812 StringRef COMDATSymName = "";
736 if (GV->isWeakForLinker()) {
737 Selection = COFF::IMAGE_COMDAT_SELECT_ANY;
738 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
739 MCSymbol *Sym = TM.getSymbol(GV, Mang);
740 COMDATSymName = Sym->getName();
813 if ((GV->isWeakForLinker() || GV->hasComdat()) && !Kind.isCommon()) {
814 Selection = getSelectionForCOFF(GV);
815 const GlobalValue *ComdatGV;
816 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
817 ComdatGV = getComdatGVForCOFF(GV);
818 else
819 ComdatGV = GV;
820
821 if (!ComdatGV->hasPrivateLinkage()) {
822 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
823 COMDATSymName = Sym->getName();
824 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
825 } else {
826 Selection = 0;
827 }
741828 }
742829 return getContext().getCOFFSection(Name,
743830 Characteristics,
774861 // into a 'uniqued' section name, create and return the section now.
775862 // Section names depend on the name of the symbol which is not feasible if the
776863 // symbol has private linkage.
777 if ((GV->isWeakForLinker() || EmitUniquedSection) &&
778 !GV->hasPrivateLinkage() && !Kind.isCommon()) {
864 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
865 !Kind.isCommon()) {
779866 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
780867 unsigned Characteristics = getCOFFSectionFlags(Kind);
781868
782869 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
783 MCSymbol *Sym = TM.getSymbol(GV, Mang);
784 return getContext().getCOFFSection(
785 Name, Characteristics, Kind, Sym->getName(),
786 GV->isWeakForLinker() ? COFF::IMAGE_COMDAT_SELECT_ANY
787 : COFF::IMAGE_COMDAT_SELECT_NODUPLICATES);
870 int Selection = getSelectionForCOFF(GV);
871 if (!Selection)
872 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
873 const GlobalValue *ComdatGV;
874 if (GV->hasComdat())
875 ComdatGV = getComdatGVForCOFF(GV);
876 else
877 ComdatGV = GV;
878
879 if (!ComdatGV->hasPrivateLinkage()) {
880 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
881 StringRef COMDATSymName = Sym->getName();
882 return getContext().getCOFFSection(Name, Characteristics, Kind,
883 COMDATSymName, Selection);
884 }
788885 }
789886
790887 if (Kind.isText())
105105
106106 enum PrefixType {
107107 GlobalPrefix,
108 ComdatPrefix,
108109 LabelPrefix,
109110 LocalPrefix,
110111 NoPrefix
118119 switch (Prefix) {
119120 case NoPrefix: break;
120121 case GlobalPrefix: OS << '@'; break;
122 case ComdatPrefix: OS << '$'; break;
121123 case LabelPrefix: break;
122124 case LocalPrefix: OS << '%'; break;
123125 }
11641166 }
11651167
11661168 void AssemblyWriter::init() {
1167 if (TheModule)
1168 TypePrinter.incorporateTypes(*TheModule);
1169 if (!TheModule)
1170 return;
1171 TypePrinter.incorporateTypes(*TheModule);
1172 for (const Function &F : *TheModule)
1173 if (const Comdat *C = F.getComdat())
1174 Comdats.insert(C);
1175 for (const GlobalVariable &GV : TheModule->globals())
1176 if (const Comdat *C = GV.getComdat())
1177 Comdats.insert(C);
11691178 }
11701179
11711180
13061315 }
13071316
13081317 printTypeIdentities();
1318
1319 // Output all comdats.
1320 if (!Comdats.empty())
1321 Out << '\n';
1322 for (const Comdat *C : Comdats) {
1323 printComdat(C);
1324 if (C != Comdats.back())
1325 Out << '\n';
1326 }
13091327
13101328 // Output all globals.
13111329 if (!M->global_empty()) Out << '\n';
14691487 PrintEscapedString(GV->getSection(), Out);
14701488 Out << '"';
14711489 }
1490 if (GV->hasComdat()) {
1491 Out << ", comdat ";
1492 PrintLLVMName(Out, GV->getComdat()->getName(), ComdatPrefix);
1493 }
14721494 if (GV->getAlignment())
14731495 Out << ", align " << GV->getAlignment();
14741496
15051527 writeOperand(Aliasee, !isa(Aliasee));
15061528 }
15071529
1530 if (GA->hasComdat()) {
1531 Out << ", comdat ";
1532 PrintLLVMName(Out, GA->getComdat()->getName(), ComdatPrefix);
1533 }
1534
15081535 printInfoComment(*GA);
15091536 Out << '\n';
1537 }
1538
1539 void AssemblyWriter::printComdat(const Comdat *C) {
1540 C->print(Out);
15101541 }
15111542
15121543 void AssemblyWriter::printTypeIdentities() {
16451676 Out << " section \"";
16461677 PrintEscapedString(F->getSection(), Out);
16471678 Out << '"';
1679 }
1680 if (F->hasComdat()) {
1681 Out << " comdat ";
1682 PrintLLVMName(Out, F->getComdat()->getName(), ComdatPrefix);
16481683 }
16491684 if (F->getAlignment())
16501685 Out << " align " << F->getAlignment();
21552190 formatted_raw_ostream OS(ROS);
21562191 AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
21572192 W.printNamedMDNode(this);
2193 }
2194
2195 void Comdat::print(raw_ostream &ROS) const {
2196 PrintLLVMName(ROS, getName(), ComdatPrefix);
2197 ROS << " = comdat ";
2198
2199 switch (getSelectionKind()) {
2200 case Comdat::Any:
2201 ROS << "any";
2202 break;
2203 case Comdat::ExactMatch:
2204 ROS << "exactmatch";
2205 break;
2206 case Comdat::Largest:
2207 ROS << "largest";
2208 break;
2209 case Comdat::NoDuplicates:
2210 ROS << "noduplicates";
2211 break;
2212 case Comdat::SameSize:
2213 ROS << "samesize";
2214 break;
2215 }
2216
2217 ROS << '\n';
21582218 }
21592219
21602220 void Type::print(raw_ostream &OS) const {
22402300 // Module::dump() - Allow printing of Modules from the debugger.
22412301 void Module::dump() const { print(dbgs(), nullptr); }
22422302
2303 // \brief Allow printing of Comdats from the debugger.
2304 void Comdat::dump() const { print(dbgs()); }
2305
22432306 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
22442307 void NamedMDNode::dump() const { print(dbgs()); }
1515 #define LLVM_IR_ASSEMBLYWRITER_H
1616
1717 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SetVector.h"
1819 #include "llvm/IR/Attributes.h"
1920 #include "llvm/IR/Instructions.h"
2021 #include "llvm/IR/TypeFinder.h"
2526 class BasicBlock;
2627 class Function;
2728 class GlobalValue;
29 class Comdat;
2830 class Module;
2931 class NamedMDNode;
3032 class Value;
6971 SlotTracker &Machine;
7072 TypePrinting TypePrinter;
7173 AssemblyAnnotationWriter *AnnotationWriter;
74 SetVector Comdats;
7275
7376 public:
7477 /// Construct an AssemblyWriter with an external SlotTracker
100103 void printTypeIdentities();
101104 void printGlobal(const GlobalVariable *GV);
102105 void printAlias(const GlobalAlias *GV);
106 void printComdat(const Comdat *C);
103107 void printFunction(const Function *F);
104108 void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
105109 void printBasicBlock(const BasicBlock *BB);
22 Attributes.cpp
33 AutoUpgrade.cpp
44 BasicBlock.cpp
5 Comdat.cpp
56 ConstantFold.cpp
67 ConstantRange.cpp
78 Constants.cpp
0 //===-- Comdat.cpp - Implement Metadata classes --------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Comdat class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/IR/Comdat.h"
14 #include "llvm/ADT/StringMap.h"
15 using namespace llvm;
16
17 Comdat::Comdat(SelectionKind SK, StringMapEntry *Name)
18 : Name(Name), SK(SK) {}
19
20 Comdat::Comdat(Comdat &&C) : Name(C.Name), SK(C.SK) {}
21
22 Comdat::Comdat() : Name(nullptr), SK(Comdat::Any) {}
23
24 StringRef Comdat::getName() const { return Name->first(); }
5858 setDLLStorageClass(Src->getDLLStorageClass());
5959 }
6060
61 static const GlobalObject *getBaseObject(const Constant &C) {
62 // FIXME: We should probably return a base + offset pair for non-zero GEPs.
63 return dyn_cast(C.stripPointerCasts());
64 }
65
6661 unsigned GlobalValue::getAlignment() const {
6762 if (auto *GA = dyn_cast(this)) {
6863 // In general we cannot compute this at the IR level, but we try.
69 if (const GlobalObject *GO = getBaseObject(*GA->getAliasee()))
64 if (const GlobalObject *GO = GA->getBaseObject())
7065 return GO->getAlignment();
7166
7267 // FIXME: we should also be able to handle:
9590 const char *GlobalValue::getSection() const {
9691 if (auto *GA = dyn_cast(this)) {
9792 // In general we cannot compute this at the IR level, but we try.
98 if (const GlobalObject *GO = getBaseObject(*GA->getAliasee()))
93 if (const GlobalObject *GO = GA->getBaseObject())
9994 return GO->getSection();
10095 return "";
10196 }
10297 return cast(this)->getSection();
98 }
99
100 Comdat *GlobalValue::getComdat() {
101 if (auto *GA = dyn_cast(this)) {
102 // In general we cannot compute this at the IR level, but we try.
103 if (const GlobalObject *GO = GA->getBaseObject())
104 return const_cast(GO)->getComdat();
105 return nullptr;
106 }
107 return cast(this)->getComdat();
103108 }
104109
105110 void GlobalObject::setSection(StringRef S) { Section = S; }
452452 return dwarf::DWARF_VERSION;
453453 return cast(Val)->getZExtValue();
454454 }
455
456 Comdat *Module::getOrInsertComdat(StringRef Name) {
457 Comdat C;
458 StringMapEntry &Entry =
459 ComdatSymTab.GetOrCreateValue(Name, std::move(C));
460 Entry.second.Name = &Entry;
461 return &Entry.second;
462 }
106106 OS << ' ' << *T;
107107 }
108108
109 void WriteComdat(const Comdat *C) {
110 if (!C)
111 return;
112 OS << *C;
113 }
114
109115 // CheckFailed - A check failed, so print out the condition and the message
110116 // that failed. This provides a nice place to put a breakpoint if you want
111117 // to see why something is not correct.
137143 WriteType(T3);
138144 Broken = true;
139145 }
146
147 void CheckFailed(const Twine &Message, const Comdat *C) {
148 OS << Message.str() << "\n";
149 WriteComdat(C);
150 Broken = true;
151 }
140152 };
141153 class Verifier : public InstVisitor, VerifierSupport {
142154 friend class InstVisitor;
228240 E = M.named_metadata_end();
229241 I != E; ++I)
230242 visitNamedMDNode(*I);
243
244 for (const StringMapEntry &SMEC : M.getComdatSymbolTable())
245 visitComdat(SMEC.getValue());
231246
232247 visitModuleFlags(M);
233248 visitModuleIdents(M);
245260 const GlobalAlias &A, const Constant &C);
246261 void visitNamedMDNode(const NamedMDNode &NMD);
247262 void visitMDNode(MDNode &MD, Function *F);
263 void visitComdat(const Comdat &C);
248264 void visitModuleIdents(const Module &M);
249265 void visitModuleFlags(const Module &M);
250266 void visitModuleFlag(const MDNode *Op,
386402 "'common' global must have a zero initializer!", &GV);
387403 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
388404 &GV);
405 Assert1(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
389406 }
390407 } else {
391408 Assert1(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
575592 Assert2(ActualF == F, "function-local metadata used in wrong function",
576593 &MD, Op);
577594 }
595 }
596
597 void Verifier::visitComdat(const Comdat &C) {
598 // All Comdat::SelectionKind values other than Comdat::Any require a
599 // GlobalValue with the same name as the Comdat.
600 const GlobalValue *GV = M->getNamedValue(C.getName());
601 if (C.getSelectionKind() != Comdat::Any)
602 Assert1(GV,
603 "comdat selection kind requires a global value with the same name",
604 &C);
605 // The Module is invalid if the GlobalValue has local linkage. Allowing
606 // otherwise opens us up to seeing the underling global value get renamed if
607 // collisions occur.
608 if (GV)
609 Assert1(!GV->hasLocalLinkage(), "comdat global value has local linkage",
610 GV);
578611 }
579612
580613 void Verifier::visitModuleIdents(const Module &M) {
425425 return true;
426426 }
427427
428 bool getComdatLeader(Module *M, StringRef ComdatName,
429 const GlobalVariable *&GVar);
430 bool computeResultingSelectionKind(StringRef ComdatName,
431 Comdat::SelectionKind Src,
432 Comdat::SelectionKind Dst,
433 Comdat::SelectionKind &Result,
434 bool &LinkFromSrc);
435 std::map>
436 ComdatsChosen;
437 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
438 bool &LinkFromSrc);
439
428440 /// getLinkageResult - This analyzes the two global values and determines
429441 /// what the result will look like in the destination module.
430442 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
533545 return DF;
534546 }
535547
548 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
549 const GlobalVariable *&GVar) {
550 const GlobalValue *GVal = M->getNamedValue(ComdatName);
551 if (const auto *GA = dyn_cast_or_null(GVal)) {
552 GVal = GA->getBaseObject();
553 if (!GVal)
554 // We cannot resolve the size of the aliasee yet.
555 return emitError("Linking COMDATs named '" + ComdatName +
556 "': COMDAT key involves incomputable alias size.");
557 }
558
559 GVar = dyn_cast_or_null(GVal);
560 if (!GVar)
561 return emitError(
562 "Linking COMDATs named '" + ComdatName +
563 "': GlobalVariable required for data dependent selection!");
564
565 return false;
566 }
567
568 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
569 Comdat::SelectionKind Src,
570 Comdat::SelectionKind Dst,
571 Comdat::SelectionKind &Result,
572 bool &LinkFromSrc) {
573 // The ability to mix Comdat::SelectionKind::Any with
574 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
575 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
576 Dst == Comdat::SelectionKind::Largest;
577 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
578 Src == Comdat::SelectionKind::Largest;
579 if (DstAnyOrLargest && SrcAnyOrLargest) {
580 if (Dst == Comdat::SelectionKind::Largest ||
581 Src == Comdat::SelectionKind::Largest)
582 Result = Comdat::SelectionKind::Largest;
583 else
584 Result = Comdat::SelectionKind::Any;
585 } else if (Src == Dst) {
586 Result = Dst;
587 } else {
588 return emitError("Linking COMDATs named '" + ComdatName +
589 "': invalid selection kinds!");
590 }
591
592 switch (Result) {
593 case Comdat::SelectionKind::Any:
594 // Go with Dst.
595 LinkFromSrc = false;
596 break;
597 case Comdat::SelectionKind::NoDuplicates:
598 return emitError("Linking COMDATs named '" + ComdatName +
599 "': noduplicates has been violated!");
600 case Comdat::SelectionKind::ExactMatch:
601 case Comdat::SelectionKind::Largest:
602 case Comdat::SelectionKind::SameSize: {
603 const GlobalVariable *DstGV;
604 const GlobalVariable *SrcGV;
605 if (getComdatLeader(DstM, ComdatName, DstGV) ||
606 getComdatLeader(SrcM, ComdatName, SrcGV))
607 return true;
608
609 const DataLayout *DstDL = DstM->getDataLayout();
610 const DataLayout *SrcDL = SrcM->getDataLayout();
611 if (!DstDL || !SrcDL) {
612 return emitError(
613 "Linking COMDATs named '" + ComdatName +
614 "': can't do size dependent selection without DataLayout!");
615 }
616 uint64_t DstSize =
617 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
618 uint64_t SrcSize =
619 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
620 if (Result == Comdat::SelectionKind::ExactMatch) {
621 if (SrcGV->getInitializer() != DstGV->getInitializer())
622 return emitError("Linking COMDATs named '" + ComdatName +
623 "': ExactMatch violated!");
624 LinkFromSrc = false;
625 } else if (Result == Comdat::SelectionKind::Largest) {
626 LinkFromSrc = SrcSize > DstSize;
627 } else if (Result == Comdat::SelectionKind::SameSize) {
628 if (SrcSize != DstSize)
629 return emitError("Linking COMDATs named '" + ComdatName +
630 "': SameSize violated!");
631 LinkFromSrc = false;
632 } else {
633 llvm_unreachable("unknown selection kind");
634 }
635 break;
636 }
637 }
638
639 return false;
640 }
641
642 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
643 Comdat::SelectionKind &Result,
644 bool &LinkFromSrc) {
645 StringRef ComdatName = SrcC->getName();
646 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
647 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
648 if (DstCI != ComdatSymTab.end()) {
649 const Comdat *DstC = &DstCI->second;
650 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
651 Comdat::SelectionKind DSK = DstC->getSelectionKind();
652 if (computeResultingSelectionKind(ComdatName, SSK, DSK, Result, LinkFromSrc))
653 return true;
654 }
655 return false;
656 }
536657
537658 /// getLinkageResult - This analyzes the two global values and determines what
538659 /// the result will look like in the destination module. In particular, it
763884 llvm::Optional NewVisibility;
764885 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
765886
887 bool LinkFromSrc = false;
888 Comdat *DC = nullptr;
889 if (const Comdat *SC = SGV->getComdat()) {
890 Comdat::SelectionKind SK;
891 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
892 DC = DstM->getOrInsertComdat(SC->getName());
893 DC->setSelectionKind(SK);
894 }
895
766896 if (DGV) {
767 // Concatenation of appending linkage variables is magic and handled later.
768 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
769 return linkAppendingVarProto(cast(DGV), SGV);
770
771 // Determine whether linkage of these two globals follows the source
772 // module's definition or the destination module's definition.
773 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
774 GlobalValue::VisibilityTypes NV;
775 bool LinkFromSrc = false;
776 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
777 return true;
778 NewVisibility = NV;
779 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
780
781 // If we're not linking from the source, then keep the definition that we
782 // have.
897 if (!DC) {
898 // Concatenation of appending linkage variables is magic and handled later.
899 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
900 return linkAppendingVarProto(cast(DGV), SGV);
901
902 // Determine whether linkage of these two globals follows the source
903 // module's definition or the destination module's definition.
904 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
905 GlobalValue::VisibilityTypes NV;
906 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
907 return true;
908 NewVisibility = NV;
909 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
910
911 // If we're not linking from the source, then keep the definition that we
912 // have.
913 if (!LinkFromSrc) {
914 // Special case for const propagation.
915 if (GlobalVariable *DGVar = dyn_cast(DGV))
916 if (DGVar->isDeclaration() && SGV->isConstant() &&
917 !DGVar->isConstant())
918 DGVar->setConstant(true);
919
920 // Set calculated linkage, visibility and unnamed_addr.
921 DGV->setLinkage(NewLinkage);
922 DGV->setVisibility(*NewVisibility);
923 DGV->setUnnamedAddr(HasUnnamedAddr);
924 }
925 }
926
783927 if (!LinkFromSrc) {
784 // Special case for const propagation.
785 if (GlobalVariable *DGVar = dyn_cast(DGV))
786 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
787 DGVar->setConstant(true);
788
789 // Set calculated linkage, visibility and unnamed_addr.
790 DGV->setLinkage(NewLinkage);
791 DGV->setVisibility(*NewVisibility);
792 DGV->setUnnamedAddr(HasUnnamedAddr);
793
794928 // Make sure to remember this mapping.
795929 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
796930
800934
801935 return false;
802936 }
937 }
938
939 // If the Comdat this variable was inside of wasn't selected, skip it.
940 if (DC && !DGV && !LinkFromSrc) {
941 DoNotLinkFromSource.insert(SGV);
942 return false;
803943 }
804944
805945 // No linking to be performed or linking from the source: simply create an
817957 NewDGV->setVisibility(*NewVisibility);
818958 NewDGV->setUnnamedAddr(HasUnnamedAddr);
819959
960 if (DC)
961 NewDGV->setComdat(DC);
962
820963 if (DGV) {
821964 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
822965 DGV->eraseFromParent();
834977 llvm::Optional NewVisibility;
835978 bool HasUnnamedAddr = SF->hasUnnamedAddr();
836979
980 bool LinkFromSrc = false;
981 Comdat *DC = nullptr;
982 if (const Comdat *SC = SF->getComdat()) {
983 Comdat::SelectionKind SK;
984 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
985 DC = DstM->getOrInsertComdat(SC->getName());
986 DC->setSelectionKind(SK);
987 }
988
837989 if (DGV) {
838 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
839 bool LinkFromSrc = false;
840 GlobalValue::VisibilityTypes NV;
841 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
842 return true;
843 NewVisibility = NV;
844 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
990 if (!DC) {
991 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
992 GlobalValue::VisibilityTypes NV;
993 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
994 return true;
995 NewVisibility = NV;
996 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
997
998 if (!LinkFromSrc) {
999 // Set calculated linkage
1000 DGV->setLinkage(NewLinkage);
1001 DGV->setVisibility(*NewVisibility);
1002 DGV->setUnnamedAddr(HasUnnamedAddr);
1003 }
1004 }
8451005
8461006 if (!LinkFromSrc) {
847 // Set calculated linkage
848 DGV->setLinkage(NewLinkage);
849 DGV->setVisibility(*NewVisibility);
850 DGV->setUnnamedAddr(HasUnnamedAddr);
851
8521007 // Make sure to remember this mapping.
8531008 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
8541009
8641019 // The ValueMaterializerTy will deal with creating it if it's used.
8651020 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
8661021 SF->hasAvailableExternallyLinkage())) {
1022 DoNotLinkFromSource.insert(SF);
1023 return false;
1024 }
1025
1026 // If the Comdat this function was inside of wasn't selected, skip it.
1027 if (DC && !DGV && !LinkFromSrc) {
8671028 DoNotLinkFromSource.insert(SF);
8681029 return false;
8691030 }
8771038 NewDF->setVisibility(*NewVisibility);
8781039 NewDF->setUnnamedAddr(HasUnnamedAddr);
8791040
1041 if (DC)
1042 NewDF->setComdat(DC);
1043
8801044 if (DGV) {
8811045 // Any uses of DF need to change to NewDF, with cast.
8821046 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
8941058 llvm::Optional NewVisibility;
8951059 bool HasUnnamedAddr = SGA->hasUnnamedAddr();
8961060
1061 bool LinkFromSrc = false;
1062 Comdat *DC = nullptr;
1063 if (const Comdat *SC = SGA->getComdat()) {
1064 Comdat::SelectionKind SK;
1065 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1066 DC = DstM->getOrInsertComdat(SC->getName());
1067 DC->setSelectionKind(SK);
1068 }
1069
8971070 if (DGV) {
898 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
899 GlobalValue::VisibilityTypes NV;
900 bool LinkFromSrc = false;
901 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
902 return true;
903 NewVisibility = NV;
904 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1071 if (!DC) {
1072 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1073 GlobalValue::VisibilityTypes NV;
1074 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1075 return true;
1076 NewVisibility = NV;
1077 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1078
1079 if (!LinkFromSrc) {
1080 // Set calculated linkage.
1081 DGV->setLinkage(NewLinkage);
1082 DGV->setVisibility(*NewVisibility);
1083 DGV->setUnnamedAddr(HasUnnamedAddr);
1084 }
1085 }
9051086
9061087 if (!LinkFromSrc) {
907 // Set calculated linkage.
908 DGV->setLinkage(NewLinkage);
909 DGV->setVisibility(*NewVisibility);
910 DGV->setUnnamedAddr(HasUnnamedAddr);
911
9121088 // Make sure to remember this mapping.
9131089 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
9141090
9171093
9181094 return false;
9191095 }
1096 }
1097
1098 // If the Comdat this alias was inside of wasn't selected, skip it.
1099 if (DC && !DGV && !LinkFromSrc) {
1100 DoNotLinkFromSource.insert(SGA);
1101 return false;
9201102 }
9211103
9221104 // If there is no linkage to be performed or we're linking from the source,
12531435 // Loop over all of the linked values to compute type mappings.
12541436 computeTypeMapping();
12551437
1438 ComdatsChosen.clear();
1439 for (const StringMapEntry &SMEC : SrcM->getComdatSymbolTable()) {
1440 const Comdat &C = SMEC.getValue();
1441 if (ComdatsChosen.count(&C))
1442 continue;
1443 Comdat::SelectionKind SK;
1444 bool LinkFromSrc;
1445 if (getComdatResult(&C, SK, LinkFromSrc))
1446 return true;
1447 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1448 }
1449
12561450 // Insert all of the globals in src into the DstM module... without linking
12571451 // initializers (which could refer to functions not yet mapped over).
12581452 for (Module::global_iterator I = SrcM->global_begin(),
7676 // Remove empty functions from the global ctors list.
7777 Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
7878
79 typedef std::multimap ComdatGVPairsTy;
80 ComdatGVPairsTy ComdatGVPairs;
81
7982 // Loop over the module, adding globals which are obviously necessary.
8083 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
8184 Changed |= RemoveUnusedGlobalValue(*I);
8285 // Functions with external linkage are needed if they have a body
83 if (!I->isDiscardableIfUnused() &&
84 !I->isDeclaration() && !I->hasAvailableExternallyLinkage())
85 GlobalIsNeeded(I);
86 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
87 if (!I->isDiscardableIfUnused())
88 GlobalIsNeeded(I);
89 else if (const Comdat *C = I->getComdat())
90 ComdatGVPairs.insert(std::make_pair(C, I));
91 }
8692 }
8793
8894 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
9096 Changed |= RemoveUnusedGlobalValue(*I);
9197 // Externally visible & appending globals are needed, if they have an
9298 // initializer.
93 if (!I->isDiscardableIfUnused() &&
94 !I->isDeclaration() && !I->hasAvailableExternallyLinkage())
95 GlobalIsNeeded(I);
99 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
100 if (!I->isDiscardableIfUnused())
101 GlobalIsNeeded(I);
102 else if (const Comdat *C = I->getComdat())
103 ComdatGVPairs.insert(std::make_pair(C, I));
104 }
96105 }
97106
98107 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
99108 I != E; ++I) {
100109 Changed |= RemoveUnusedGlobalValue(*I);
101110 // Externally visible aliases are needed.
102 if (!I->isDiscardableIfUnused())
111 if (!I->isDiscardableIfUnused()) {
103112 GlobalIsNeeded(I);
113 } else if (const Comdat *C = I->getComdat()) {
114 ComdatGVPairs.insert(std::make_pair(C, I));
115 }
116 }
117
118 for (ComdatGVPairsTy::iterator I = ComdatGVPairs.begin(),
119 E = ComdatGVPairs.end();
120 I != E;) {
121 ComdatGVPairsTy::iterator UB = ComdatGVPairs.upper_bound(I->first);
122 bool CanDiscard = std::all_of(I, UB, [](ComdatGVPairsTy::value_type Pair) {
123 return Pair.second->isDiscardableIfUnused();
124 });
125 if (!CanDiscard) {
126 std::for_each(I, UB, [this](ComdatGVPairsTy::value_type Pair) {
127 GlobalIsNeeded(Pair.second);
128 });
129 }
130 I = UB;
104131 }
105132
106133 // Now that all globals which are needed are in the AliveGlobals set, we loop
1616 #include "llvm/ADT/DenseMap.h"
1717 #include "llvm/ADT/STLExtras.h"
1818 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallSet.h"
1920 #include "llvm/ADT/SmallVector.h"
2021 #include "llvm/ADT/Statistic.h"
2122 #include "llvm/Analysis/ConstantFolding.h"
16981699 /// possible. If we make a change, return true.
16991700 bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
17001701 Module::global_iterator &GVI) {
1701 if (!GV->isDiscardableIfUnused())
1702 return false;
1703
17041702 // Do more involved optimizations if the global is internal.
17051703 GV->removeDeadConstantUsers();
17061704
19431941
19441942 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
19451943 bool Changed = false;
1944
1945 SmallSet NotDiscardableComdats;
1946 for (const GlobalVariable &GV : M.globals())
1947 if (const Comdat *C = GV.getComdat())
1948 if (!GV.isDiscardableIfUnused())
1949 NotDiscardableComdats.insert(C);
1950
19461951 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
19471952 GVI != E; ) {
19481953 GlobalVariable *GV = GVI++;
19571962 GV->setInitializer(New);
19581963 }
19591964
1960 Changed |= ProcessGlobal(GV, GVI);
1965 if (GV->isDiscardableIfUnused()) {
1966 if (const Comdat *C = GV->getComdat())
1967 if (NotDiscardableComdats.count(C))
1968 continue;
1969 Changed |= ProcessGlobal(GV, GVI);
1970 }
19611971 }
19621972 return Changed;
19631973 }
0 ; RUN: not llvm-as < %s 2>&1 | FileCheck %s
1
2 @v = global i32 0, comdat $v
3 ; CHECK: use of undefined comdat '$v'
0 ; RUN: not llvm-as < %s 2>&1 | FileCheck %s
1
2 $v = comdat any
3 $v = comdat any
4 ; CHECK: redefinition of comdat '$v'
0 ; RUN: llc -mtriple i386-pc-win32 < %s | FileCheck %s
1
2 $f1 = comdat any
3 @v1 = global i32 0, comdat $f1
4 define void @f1() comdat $f1 {
5 ret void
6 }
7
8 $f2 = comdat exactmatch
9 @v2 = global i32 0, comdat $f2
10 define void @f2() comdat $f2 {
11 ret void
12 }
13
14 $f3 = comdat largest
15 @v3 = global i32 0, comdat $f3
16 define void @f3() comdat $f3 {
17 ret void
18 }
19
20 $f4 = comdat noduplicates
21 @v4 = global i32 0, comdat $f4
22 define void @f4() comdat $f4 {
23 ret void
24 }
25
26 $f5 = comdat samesize
27 @v5 = global i32 0, comdat $f5
28 define void @f5() comdat $f5 {
29 ret void
30 }
31
32 $f6 = comdat samesize
33 @v6 = global i32 0, comdat $f6
34 @f6 = global i32 0, comdat $f6
35
36 $"\01@f7@0" = comdat any
37 define x86_fastcallcc void @"\01@v7@0"() comdat $"\01@f7@0" {
38 ret void
39 }
40 define x86_fastcallcc void @"\01@f7@0"() comdat $"\01@f7@0" {
41 ret void
42 }
43
44 $f8 = comdat any
45 define x86_fastcallcc void @v8() comdat $f8 {
46 ret void
47 }
48 define x86_fastcallcc void @f8() comdat $f8 {
49 ret void
50 }
51
52 $vftable = comdat largest
53
54 @some_name = private unnamed_addr constant [2 x i8*] zeroinitializer, comdat $vftable
55 @vftable = alias getelementptr([2 x i8*]* @some_name, i32 0, i32 1)
56
57 ; CHECK: .section .text,"xr",discard,_f1
58 ; CHECK: .globl _f1
59 ; CHECK: .section .text,"xr",same_contents,_f2
60 ; CHECK: .globl _f2
61 ; CHECK: .section .text,"xr",largest,_f3
62 ; CHECK: .globl _f3
63 ; CHECK: .section .text,"xr",one_only,_f4
64 ; CHECK: .globl _f4
65 ; CHECK: .section .text,"xr",same_size,_f5
66 ; CHECK: .globl _f5
67 ; CHECK: .section .text,"xr",associative,@f7@0
68 ; CHECK: .globl @v7@0
69 ; CHECK: .section .text,"xr",discard,@f7@0
70 ; CHECK: .globl @f7@0
71 ; CHECK: .section .text,"xr",associative,@f8@0
72 ; CHECK: .globl @v8@0
73 ; CHECK: .section .text,"xr",discard,@f8@0
74 ; CHECK: .globl @f8@0
75 ; CHECK: .section .bss,"bw",associative,_f1
76 ; CHECK: .globl _v1
77 ; CHECK: .section .bss,"bw",associative,_f2
78 ; CHECK: .globl _v2
79 ; CHECK: .section .bss,"bw",associative,_f3
80 ; CHECK: .globl _v3
81 ; CHECK: .section .bss,"bw",associative,_f4
82 ; CHECK: .globl _v4
83 ; CHECK: .section .bss,"bw",associative,_f5
84 ; CHECK: .globl _v5
85 ; CHECK: .section .bss,"bw",associative,_f6
86 ; CHECK: .globl _v6
87 ; CHECK: .section .bss,"bw",same_size,_f6
88 ; CHECK: .globl _f6
89 ; CHECK: .section .rdata,"rd",largest,_vftable
90 ; CHECK: .globl _vftable
91 ; CHECK: _vftable = L_some_name+4
0 .text
1 .def @feat.00;
2 .scl 3;
3 .type 0;
4 .endef
5 .globl @feat.00
6 @feat.00 = 1
7 .def _f1;
8 .scl 2;
9 .type 32;
10 .endef
11 .section .text,"xr",discard,_f1
12 .globl _f1
13 .align 16, 0x90
14 _f1: # @f1
15 # BB#0:
16 retl
17
18 .def _f2;
19 .scl 2;
20 .type 32;
21 .endef
22 .section .text,"xr",same_contents,_f2
23 .globl _f2
24 .align 16, 0x90
25 _f2: # @f2
26 # BB#0:
27 retl
28
29 .def _f3;
30 .scl 2;
31 .type 32;
32 .endef
33 .section .text,"xr",largest,_f3
34 .globl _f3
35 .align 16, 0x90
36 _f3: # @f3
37 # BB#0:
38 retl
39
40 .def _f4;
41 .scl 2;
42 .type 32;
43 .endef
44 .section .text,"xr",one_only,_f4
45 .globl _f4
46 .align 16, 0x90
47 _f4: # @f4
48 # BB#0:
49 retl
50
51 .def _f5;
52 .scl 2;
53 .type 32;
54 .endef
55 .section .text,"xr",same_size,_f5
56 .globl _f5
57 .align 16, 0x90
58 _f5: # @f5
59 # BB#0:
60 retl
61
62 .def @v7@0;
63 .scl 2;
64 .type 32;
65 .endef
66 .section .text,"xr",associative,@f7@0
67 .globl @v7@0
68 .align 16, 0x90
69 @v7@0: # @"\01@v7@0"
70 # BB#0:
71 retl
72
73 .def @f7@0;
74 .scl 2;
75 .type 32;
76 .endef
77 .section .text,"xr",discard,@f7@0
78 .globl @f7@0
79 .align 16, 0x90
80 @f7@0: # @"\01@f7@0"
81 # BB#0:
82 retl
83
84 .def @v8@0;
85 .scl 2;
86 .type 32;
87 .endef
88 .section .text,"xr",associative,@f8@0
89 .globl @v8@0
90 .align 16, 0x90
91 @v8@0: # @v8
92 # BB#0:
93 retl
94
95 .def @f8@0;
96 .scl 2;
97 .type 32;
98 .endef
99 .section .text,"xr",discard,@f8@0
100 .globl @f8@0
101 .align 16, 0x90
102 @f8@0: # @f8
103 # BB#0:
104 retl
105
106 .section .bss,"bw",associative,_f1
107 .globl _v1 # @v1
108 .align 4
109 _v1:
110 .long 0 # 0x0
111
112 .section .bss,"bw",associative,_f2
113 .globl _v2 # @v2
114 .align 4
115 _v2:
116 .long 0 # 0x0
117
118 .section .bss,"bw",associative,_f3
119 .globl _v3 # @v3
120 .align 4
121 _v3:
122 .long 0 # 0x0
123
124 .section .bss,"bw",associative,_f4
125 .globl _v4 # @v4
126 .align 4
127 _v4:
128 .long 0 # 0x0
129
130 .section .bss,"bw",associative,_f5
131 .globl _v5 # @v5
132 .align 4
133 _v5:
134 .long 0 # 0x0
135
136 .section .bss,"bw",associative,_f6
137 .globl _v6 # @v6
138 .align 4
139 _v6:
140 .long 0 # 0x0
141
142 .section .bss,"bw",same_size,_f6
143 .globl _f6 # @f6
144 .align 4
145 _f6:
146 .long 0 # 0x0
147
148 .section .rdata,"rd"
149 .align 4 # @some_name
150 L_some_name:
151 .zero 8
152
153
154 .globl _vftable
155 _vftable = L_some_name+4
0 ; RUN: not llc %s -o /dev/null 2>&1 | FileCheck %s
1
2 target datalayout = "e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32"
3 target triple = "i686-pc-windows-msvc"
4
5 $foo = comdat largest
6 @foo = global i32 0
7 @bar = global i32 0, comdat $foo
8 ; CHECK: Associative COMDAT symbol 'foo' is not a key for it's COMDAT.
0 ; RUN: not llc %s -o /dev/null 2>&1 | FileCheck %s
1
2 target datalayout = "e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32"
3 target triple = "i686-pc-windows-msvc"
4
5 $foo = comdat largest
6 @bar = global i32 0, comdat $foo
7 ; CHECK: Associative COMDAT symbol 'foo' does not exist.
0 ; RUN: llc -mtriple x86_64-pc-linux-gnu < %s | FileCheck %s
1
2 $f = comdat any
3 @v = global i32 0, comdat $f
4 define void @f() comdat $f {
5 ret void
6 }
7 ; CHECK: .section .text.f,"axG",@progbits,f,comdat
8 ; CHECK: .globl f
9 ; CHECK: .section .bss.v,"aGw",@nobits,f,comdat
10 ; CHECK: .globl v
0 ; RUN: llc -mtriple x86_64-pc-linux-gnu < %s | FileCheck %s
1
2 $foo = comdat any
3 @bar = global i32 42, comdat $foo
4 @foo = global i32 42
5
6 ; CHECK: .type bar,@object
7 ; CHECK-NEXT: .section .data.bar,"aGw",@progbits,foo,comdat
8 ; CHECK-NEXT: .globl bar
9 ; CHECK: .type foo,@object
10 ; CHECK-NEXT: .data
11 ; CHECK-NEXT: .globl foo
0 ; RUN: not llc -mtriple x86_64-apple-darwin < %s 2> %t
1 ; RUN: FileCheck < %t %s
2
3 $f = comdat any
4 @v = global i32 0, comdat $f
5 ; CHECK: LLVM ERROR: MachO doesn't support COMDATs, 'f' cannot be lowered.
0 ; RUN: llvm-as < %s | llvm-dis | FileCheck %s
1
2 $f = comdat any
3 ; CHECK: $f = comdat any
4
5 $f2 = comdat any
6 ; CHECK-NOT: f2
7
8 @v = global i32 0, comdat $f
9 ; CHECK: @v = global i32 0, comdat $f
10
11 define void @f() comdat $f {
12 ret void
13 }
14 ; CHECK: define void @f() comdat $f
44 target triple = "x86_64-unknown-linux-gnu"
55
66 @.str_noinst = private unnamed_addr constant [4 x i8] c"aaa\00", section "llvm.metadata"
7 @.str_inst = private unnamed_addr constant [4 x i8] c"aaa\00",
7 @.str_inst = private unnamed_addr constant [4 x i8] c"aaa\00"
88
99 ; CHECK-NOT: {{asan_gen.*str_noinst}}
1010 ; CHECK: {{asan_gen.*str_inst}}
0 target datalayout = "e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32"
1 target triple = "i686-pc-windows-msvc"
2
3 $foo = comdat largest
4 @foo = global i64 43, comdat $foo
5
6 define i32 @bar() comdat $foo {
7 ret i32 43
8 }
9
10 $qux = comdat largest
11 @qux = global i32 13, comdat $qux
12 @in_unselected_group = global i32 13, comdat $qux
13
14 define i32 @baz() comdat $qux {
15 ret i32 13
16 }
17
18 $any = comdat any
19 @any = global i64 7, comdat $any
0 $foo = comdat largest
1 @foo = global i64 43, comdat $foo
0 $foo = comdat noduplicates
1 @foo = global i64 43, comdat $foo
0 target datalayout = "e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32"
1 target triple = "i686-pc-windows-msvc"
2
3 $foo = comdat samesize
4 @foo = global i64 42, comdat $foo
0 target datalayout = "e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32"
1 target triple = "i686-pc-windows-msvc"
2
3 %MSRTTICompleteObjectLocator = type { i32, i32, i32, i8*, %MSRTTIClassHierarchyDescriptor* }
4 %MSRTTIClassHierarchyDescriptor = type { i32, i32, i32, %MSRTTIBaseClassDescriptor** }
5 %MSRTTIBaseClassDescriptor = type { i8*, i32, i32, i32, i32, i32, %MSRTTIClassHierarchyDescriptor* }
6 %struct.S = type { i32 (...)** }
7
8 $"\01??_7S@@6B@" = comdat largest
9
10 @"\01??_R4S@@6B@" = external constant %MSRTTICompleteObjectLocator
11 @some_name = private unnamed_addr constant [2 x i8*] [i8* bitcast (%MSRTTICompleteObjectLocator* @"\01??_R4S@@6B@" to i8*), i8* bitcast (void (%struct.S*, i32)* @"\01??_GS@@UAEPAXI@Z" to i8*)], comdat $"\01??_7S@@6B@"
12 @"\01??_7S@@6B@" = alias getelementptr([2 x i8*]* @some_name, i32 0, i32 1)
13
14 declare x86_thiscallcc void @"\01??_GS@@UAEPAXI@Z"(%struct.S*, i32) unnamed_addr
0 ; RUN: llvm-link %s %p/Inputs/comdat.ll -S -o - | FileCheck %s
1 target datalayout = "e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32"
2 target triple = "i686-pc-windows-msvc"
3
4 $foo = comdat largest
5 @foo = global i32 42, comdat $foo
6
7 define i32 @bar() comdat $foo {
8 ret i32 42
9 }
10
11 $qux = comdat largest
12 @qux = global i64 12, comdat $qux
13
14 define i32 @baz() comdat $qux {
15 ret i32 12
16 }
17
18 $any = comdat any
19 @any = global i64 6, comdat $any
20
21 ; CHECK: $qux = comdat largest
22 ; CHECK: $foo = comdat largest
23 ; CHECK: $any = comdat any
24
25 ; CHECK: @qux = global i64 12, comdat $qux
26 ; CHECK: @any = global i64 6, comdat $any
27 ; CHECK: @foo = global i64 43, comdat $foo
28 ; CHECK-NOT: @in_unselected_group = global i32 13, comdat $qux
29
30 ; CHECK: define i32 @baz() comdat $qux
31 ; CHECK: define i32 @bar() comdat $foo
0 ; RUN: not llvm-link %s %p/Inputs/comdat.ll -S -o - 2>&1 | FileCheck %s
1 target datalayout = "e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32"
2 target triple = "i686-pc-windows-msvc"
3
4 $foo = comdat samesize
5 @foo = global i32 42, comdat $foo
6 ; CHECK: Linking COMDATs named 'foo': invalid selection kinds!
0 ; RUN: not llvm-link %s %p/Inputs/comdat2.ll -S -o - 2>&1 | FileCheck %s
1
2 $foo = comdat largest
3 @foo = global i32 43, comdat $foo
4 ; CHECK: Linking COMDATs named 'foo': can't do size dependent selection without DataLayout!
0 ; RUN: not llvm-link %s %p/Inputs/comdat3.ll -S -o - 2>&1 | FileCheck %s
1
2 $foo = comdat noduplicates
3 @foo = global i64 43, comdat $foo
4 ; CHECK: Linking COMDATs named 'foo': noduplicates has been violated!
0 ; RUN: not llvm-link %s %p/Inputs/comdat4.ll -S -o - 2>&1 | FileCheck %s
1 target datalayout = "e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32"
2 target triple = "i686-pc-windows-msvc"
3
4 $foo = comdat samesize
5 @foo = global i32 42, comdat $foo
6 ; CHECK: Linking COMDATs named 'foo': SameSize violated!
0 ; RUN: llvm-link %s %p/Inputs/comdat5.ll -S -o - 2>&1 | FileCheck %s
1 ; RUN: llvm-link %p/Inputs/comdat5.ll %s -S -o - 2>&1 | FileCheck %s
2 target datalayout = "e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32"
3 target triple = "i686-pc-windows-msvc"
4
5 %struct.S = type { i32 (...)** }
6
7 $"\01??_7S@@6B@" = comdat largest
8 @"\01??_7S@@6B@" = linkonce_odr unnamed_addr constant [1 x i8*] [i8* bitcast (void (%struct.S*, i32)* @"\01??_GS@@UAEPAXI@Z" to i8*)], comdat $"\01??_7S@@6B@"
9
10 ; CHECK: @"\01??_7S@@6B@" = alias getelementptr inbounds ([2 x i8*]* @some_name, i32 0, i32 1)
11
12 declare x86_thiscallcc void @"\01??_GS@@UAEPAXI@Z"(%struct.S*, i32) unnamed_addr
0 ; RUN: not llvm-link %s %p/Inputs/comdat5.ll -S -o - 2>&1 | FileCheck %s
1 target datalayout = "e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32"
2 target triple = "i686-pc-windows-msvc"
3
4 $"\01??_7S@@6B@" = comdat largest
5 define void @"\01??_7S@@6B@"() {
6 ret void
7 }
8 ; CHECK: GlobalVariable required for data dependent selection!
0 ; RUN: not llvm-link %s %p/Inputs/comdat5.ll -S -o - 2>&1 | FileCheck %s
1 target datalayout = "e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32"
2 target triple = "i686-pc-windows-msvc"
3
4 $"\01??_7S@@6B@" = comdat largest
5 define void @some_name() {
6 ret void
7 }
8 @"\01??_7S@@6B@" = alias i8* inttoptr (i32 ptrtoint (void ()* @some_name to i32) to i8*)
9 ; CHECK: COMDAT key involves incomputable alias size.
0 ; RUN: not llvm-as %s -o /dev/null 2>&1 | FileCheck %s
1
2 $v = comdat any
3 @v = common global i32 0, comdat $v
4 ; CHECK: 'common' global may not be in a Comdat!
0 ; RUN: not llvm-as %s -o /dev/null 2>&1 | FileCheck %s
1
2 $v = comdat any
3 @v = private global i32 0, comdat $v
4 ; CHECK: comdat global value has local linkage