llvm.org GIT mirror llvm / dc62a47
[ADT] Make Twine's copy constructor private. There's a lot of misuse of Twine scattered around LLVM. This ranges in severity from benign (returning a Twine from a function by value that is just a string literal) to pretty sketchy (storing a Twine by value in a class). While there are some uses for copying Twines, most of the very compelling ones are confined to the Twine class implementation itself, and other uses are either dubious or easily worked around. This patch makes Twine's copy constructor private, and fixes up all callsites. Differential Revision: https://reviews.llvm.org/D38767 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@315530 91177308-0d34-0410-b5e6-96231b3b80d8 Zachary Turner 1 year, 11 months ago
17 changed file(s) with 72 addition(s) and 47 deletion(s). Raw diff Collapse all Expand all
7878 /// overloads) to guarantee that particularly important cases (cstring plus
7979 /// StringRef) codegen as desired.
8080 class Twine {
81 friend Twine operator+(const char *LHS, const StringRef &RHS);
82 friend Twine operator+(const StringRef &LHS, const char *RHS);
83 friend Twine operator+(const StringRef &LHS, const StringRef &RHS);
84
8185 /// NodeKind - Represent the type of an argument.
8286 enum NodeKind : unsigned char {
8387 /// An empty string; the result of concatenating anything with it is also
168172 assert(isNullary() && "Invalid kind!");
169173 }
170174
175 // While there are some valid use cases for copying Twines, most of them
176 // are confined to the implementation of Twine itself, and Twine itself is
177 // not intended to be publicly copyable since it can very easily lead to
178 // dangling pointers / references.
179 Twine(const Twine &) = default;
180
171181 /// Construct a binary twine.
172182 explicit Twine(const Twine &LHS, const Twine &RHS)
173183 : LHSKind(TwineKind), RHSKind(TwineKind) {
254264 /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
255265 assert(isValid() && "Invalid twine!");
256266 }
257
258 Twine(const Twine &) = default;
259267
260268 /// Construct from a C string.
261269 ///
273281 assert(isValid() && "Invalid twine!");
274282 }
275283
284 Twine(Twine &&Other) = default;
285
276286 /// Construct from an std::string.
277287 /*implicit*/ Twine(const std::string &Str)
278288 : LHSKind(StdStringKind), RHSKind(EmptyKind) {
373383 : LHSKind(StringRefKind), RHSKind(CStringKind) {
374384 this->LHS.stringRef = &LHS;
375385 this->RHS.cString = RHS;
386 assert(isValid() && "Invalid twine!");
387 }
388
389 /// Construct as the concatenation of two StringRefs.
390 /*implicit*/ Twine(const StringRef &LHS, const StringRef &RHS)
391 : LHSKind(StringRefKind), RHSKind(StringRefKind) {
392 this->LHS.stringRef = &LHS;
393 this->RHS.stringRef = &RHS;
376394 assert(isValid() && "Invalid twine!");
377395 }
378396
486504 /// Dump the representation of this twine to stderr.
487505 void dumpRepr() const;
488506
507 friend inline Twine operator+(const Twine &LHS, const Twine &RHS) {
508 return LHS.concat(RHS);
509 }
510
489511 /// @}
490512 };
491513
521543 return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
522544 }
523545
524 inline Twine operator+(const Twine &LHS, const Twine &RHS) {
525 return LHS.concat(RHS);
526 }
527
528546 /// Additional overload to guarantee simplified codegen; this is equivalent to
529547 /// concat().
530548
532550 return Twine(LHS, RHS);
533551 }
534552
535 /// Additional overload to guarantee simplified codegen; this is equivalent to
536 /// concat().
537
538553 inline Twine operator+(const StringRef &LHS, const char *RHS) {
554 return Twine(LHS, RHS);
555 }
556
557 inline Twine operator+(const StringRef &LHS, const StringRef &RHS) {
539558 return Twine(LHS, RHS);
540559 }
541560
961961 /// Diagnostic information for unsupported feature in backend.
962962 class DiagnosticInfoUnsupported : public DiagnosticInfoWithLocationBase {
963963 private:
964 Twine Msg;
964 std::string Msg;
965965
966966 public:
967967 /// \p Fn is the function where the diagnostic is being emitted. \p Loc is
975975 const DiagnosticLocation &Loc = DiagnosticLocation(),
976976 DiagnosticSeverity Severity = DS_Error)
977977 : DiagnosticInfoWithLocationBase(DK_Unsupported, Severity, Fn, Loc),
978 Msg(Msg) {}
978 Msg(Msg.str()) {}
979979
980980 static bool classof(const DiagnosticInfo *DI) {
981981 return DI->getKind() == DK_Unsupported;
982982 }
983983
984 const Twine &getMessage() const { return Msg; }
984 StringRef getMessage() const { return Msg; }
985985
986986 void print(DiagnosticPrinter &DP) const override;
987987 };
6464 class GenericBinaryError : public ErrorInfo {
6565 public:
6666 static char ID;
67 GenericBinaryError(Twine Msg);
68 GenericBinaryError(Twine Msg, object_error ECOverride);
67 GenericBinaryError(const Twine &Msg);
68 GenericBinaryError(const Twine &Msg, object_error ECOverride);
6969 const std::string &getMessage() const { return Msg; }
7070 void log(raw_ostream &OS) const override;
7171 private:
8686
8787 class EmptyResError : public GenericBinaryError {
8888 public:
89 EmptyResError(Twine Msg, object_error ECOverride)
89 EmptyResError(const Twine &Msg, object_error ECOverride)
9090 : GenericBinaryError(Msg, ECOverride) {}
9191 };
9292
930930 /// This is useful in the base level of your program to allow clean termination
931931 /// (allowing clean deallocation of resources, etc.), while reporting error
932932 /// information to the user.
933 void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner);
933 void logAllUnhandledErrors(Error E, raw_ostream &OS, const Twine &ErrorBanner);
934934
935935 /// Write all error messages (if any) in E to a string. The newline character
936936 /// is used to separate error messages.
2727 };
2828
2929 template class provider_format_adapter : public format_adapter {
30 T Item;
30 T &Item;
3131
3232 public:
3333 explicit provider_format_adapter(T &&Item) : Item(Item) {}
5959 char BinaryError::ID = 0;
6060 char GenericBinaryError::ID = 0;
6161
62 GenericBinaryError::GenericBinaryError(Twine Msg) : Msg(Msg.str()) {}
62 GenericBinaryError::GenericBinaryError(const Twine &Msg) : Msg(Msg.str()) {}
6363
64 GenericBinaryError::GenericBinaryError(Twine Msg, object_error ECOverride)
64 GenericBinaryError::GenericBinaryError(const Twine &Msg,
65 object_error ECOverride)
6566 : Msg(Msg.str()) {
6667 setErrorCode(make_error_code(ECOverride));
6768 }
5353 char ECError::ID = 0;
5454 char StringError::ID = 0;
5555
56 void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner) {
56 void logAllUnhandledErrors(Error E, raw_ostream &OS, const Twine &ErrorBanner) {
5757 if (!E)
5858 return;
5959 OS << ErrorBanner;
119119 << Ptr.cString << "\"";
120120 break;
121121 case Twine::StdStringKind:
122 OS << "std::string:\""
123 << Ptr.stdString << "\"";
122 OS << "std::string:\"" << *Ptr.stdString << "\"";
124123 break;
125124 case Twine::StringRefKind:
126 OS << "stringref:\""
127 << Ptr.stringRef << "\"";
125 OS << "stringref:\"" << *Ptr.stringRef << "\"";
128126 break;
129127 case Twine::SmallStringKind:
130128 OS << "smallstring:\"" << *Ptr.smallString << "\"";
129129 class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
130130 std::string Prefix;
131131
132 const Twine getNameWithPrefix(const Twine &Name) const {
133 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
134 }
135
136132 public:
137133 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
138134
139135 protected:
140136 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
141137 BasicBlock::iterator InsertPt) const {
142 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
143 InsertPt);
138 const Twine &Prefixed = Prefix + Name;
139 IRBuilderDefaultInserter::InsertHelper(
140 I, Name.isTriviallyEmpty() ? Name : Prefixed, BB, InsertPt);
144141 }
145142 };
146143
13541351 /// This will return the BasePtr if that is valid, or build a new GEP
13551352 /// instruction using the IRBuilder if GEP-ing is needed.
13561353 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1357 SmallVectorImpl &Indices, Twine NamePrefix) {
1354 SmallVectorImpl &Indices,
1355 const Twine &NamePrefix) {
13581356 if (Indices.empty())
13591357 return BasePtr;
13601358
13791377 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
13801378 Value *BasePtr, Type *Ty, Type *TargetTy,
13811379 SmallVectorImpl &Indices,
1382 Twine NamePrefix) {
1380 const Twine &NamePrefix) {
13831381 if (Ty == TargetTy)
13841382 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
13851383
14241422 Value *Ptr, Type *Ty, APInt &Offset,
14251423 Type *TargetTy,
14261424 SmallVectorImpl &Indices,
1427 Twine NamePrefix) {
1425 const Twine &NamePrefix) {
14281426 if (Offset == 0)
14291427 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
14301428 NamePrefix);
14971495 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
14981496 Value *Ptr, APInt Offset, Type *TargetTy,
14991497 SmallVectorImpl &Indices,
1500 Twine NamePrefix) {
1498 const Twine &NamePrefix) {
15011499 PointerType *Ty = cast(Ptr->getType());
15021500
15031501 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
15351533 /// a single GEP as possible, thus making each GEP more independent of the
15361534 /// surrounding code.
15371535 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1538 APInt Offset, Type *PointerTy, Twine NamePrefix) {
1536 APInt Offset, Type *PointerTy,
1537 const Twine &NamePrefix) {
15391538 // Even though we don't look through PHI nodes, we could be called on an
15401539 // instruction in an unreachable block, which may be on a cycle.
15411540 SmallPtrSet Visited;
194194 std::string ToolName;
195195 } // anonymous namespace
196196
197 static void error(Twine Message, Twine Path = Twine()) {
197 static void error(const Twine &Message, const Twine &Path = Twine()) {
198198 HadError = true;
199199 errs() << ToolName << ": " << Path << ": " << Message << ".\n";
200200 }
201201
202 static bool error(std::error_code EC, Twine Path = Twine()) {
202 static bool error(std::error_code EC, const Twine &Path = Twine()) {
203203 if (EC) {
204204 error(EC.message(), Path);
205205 return true;
427427 }
428428 }
429429
430 SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
430 SectionBase *SectionTableRef::getSection(uint16_t Index, const Twine &ErrMsg) {
431431 if (Index == SHN_UNDEF || Index > Sections.size())
432432 error(ErrMsg);
433433 return Sections[Index - 1].get();
434434 }
435435
436436 template
437 T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
438 Twine TypeErrMsg) {
437 T *SectionTableRef::getSectionOfType(uint16_t Index, const Twine &IndexErrMsg,
438 const Twine &TypeErrMsg) {
439439 if (T *Sec = llvm::dyn_cast(getSection(Index, IndexErrMsg)))
440440 return Sec;
441441 error(TypeErrMsg);
2828 : Sections(Secs) {}
2929 SectionTableRef(const SectionTableRef &) = default;
3030
31 SectionBase *getSection(uint16_t Index, llvm::Twine ErrMsg);
31 SectionBase *getSection(uint16_t Index, const llvm::Twine &ErrMsg);
3232
3333 template
34 T *getSectionOfType(uint16_t Index, llvm::Twine IndexErrMsg,
35 llvm::Twine TypeErrMsg);
34 T *getSectionOfType(uint16_t Index, const llvm::Twine &IndexErrMsg,
35 const llvm::Twine &TypeErrMsg);
3636 };
3737
3838 class SectionBase {
2626
2727 namespace llvm {
2828
29 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
29 LLVM_ATTRIBUTE_NORETURN void error(const Twine &Message) {
3030 errs() << ToolName << ": " << Message << ".\n";
3131 errs().flush();
3232 exit(1);
1313
1414 namespace llvm {
1515
16 LLVM_ATTRIBUTE_NORETURN extern void error(Twine Message);
16 LLVM_ATTRIBUTE_NORETURN extern void error(const Twine &Message);
1717
1818 // This is taken from llvm-readobj.
1919 // [see here](llvm/tools/llvm-readobj/llvm-readobj.h:38)
8787 repr(Twine("a").concat(Twine(SmallString<3>("b")).concat(Twine("c")))));
8888 }
8989
90 TEST(TwineTest, Operators) {
91 EXPECT_EQ(R"((Twine cstring:"a" stringref:"b"))", repr("a" + StringRef("b")));
92
93 EXPECT_EQ(R"((Twine stringref:"a" cstring:"b"))", repr(StringRef("a") + "b"));
94 EXPECT_EQ(R"((Twine stringref:"a" stringref:"b"))",
95 repr(StringRef("a") + StringRef("b")));
96 }
97
9098 TEST(TwineTest, toNullTerminatedStringRef) {
9199 SmallString<8> storage;
92100 EXPECT_EQ(0, *Twine("hello").toNullTerminatedStringRef(storage).end());
168168 /// to the class.
169169 static void visitRegisterBankClasses(
170170 CodeGenRegBank &RegisterClassHierarchy, const CodeGenRegisterClass *RC,
171 const Twine Kind,
171 const Twine &Kind,
172172 std::function VisitFn,
173173 SmallPtrSetImpl &VisitedRCs) {
174174
182182
183183 for (const auto &PossibleSubclass : RegisterClassHierarchy.getRegClasses()) {
184184 std::string TmpKind =
185 (Twine(Kind) + " (" + PossibleSubclass.getName() + ")").str();
185 (Kind + " (" + PossibleSubclass.getName() + ")").str();
186186
187187 // Visit each subclass of an explicitly named class.
188188 if (RC != &PossibleSubclass && RC->hasSubClass(&PossibleSubclass))