Index: clang-tools-extra/change-namespace/tool/ClangChangeNamespace.cpp =================================================================== --- clang-tools-extra/change-namespace/tool/ClangChangeNamespace.cpp +++ clang-tools-extra/change-namespace/tool/ClangChangeNamespace.cpp @@ -70,7 +70,7 @@ } // anonymous namespace int main(int argc, const char **argv) { - llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); + llvm::sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0])); tooling::CommonOptionsParser OptionsParser(argc, argv, ChangeNamespaceCategory); const auto &Files = OptionsParser.getSourcePathList(); Index: clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp =================================================================== --- clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp +++ clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp @@ -62,9 +62,9 @@ "code when -style=file.\n"), cl::init(""), cl::cat(FormattingCategory)); -static cl::opt -FormatStyleOpt("style", cl::desc(format::StyleOptionHelpDescription), - cl::init("LLVM"), cl::cat(FormattingCategory)); +static cl::opt FormatStyleOpt( + "style", cl::desc(llvm::StringRef(format::StyleOptionHelpDescription)), + cl::init("LLVM"), cl::cat(FormattingCategory)); namespace { // Helper object to remove the TUReplacement files (triggered by Index: clang-tools-extra/clang-move/tool/ClangMoveMain.cpp =================================================================== --- clang-tools-extra/clang-move/tool/ClangMoveMain.cpp +++ clang-tools-extra/clang-move/tool/ClangMoveMain.cpp @@ -73,7 +73,7 @@ } // namespace int main(int argc, const char **argv) { - llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); + llvm::sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0])); // Add "-fparse-all-comments" compile option to make clang parse all comments, // otherwise, ordinary comments like "//" and "/*" won't get parsed (This is // a bit of hacky). Index: clang-tools-extra/clang-query/tool/ClangQuery.cpp =================================================================== --- clang-tools-extra/clang-query/tool/ClangQuery.cpp +++ clang-tools-extra/clang-query/tool/ClangQuery.cpp @@ -46,7 +46,7 @@ using namespace clang::tooling; using namespace llvm; -static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); +static cl::extrahelp CommonHelp((StringRef(CommonOptionsParser::HelpMessage))); static cl::OptionCategory ClangQueryCategory("clang-query options"); static cl::list Commands("c", cl::desc("Specify command to run"), @@ -59,7 +59,7 @@ cl::cat(ClangQueryCategory)); int main(int argc, const char **argv) { - llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); + llvm::sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0])); CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory); @@ -80,7 +80,7 @@ for (cl::list::iterator I = Commands.begin(), E = Commands.end(); I != E; ++I) { - QueryRef Q = QueryParser::parse(I->c_str(), QS); + QueryRef Q = QueryParser::parse(llvm::StringRef(I->c_str()), QS); if (!Q->run(llvm::outs(), QS)) return 1; } @@ -97,7 +97,7 @@ std::string Line; std::getline(Input, Line); - QueryRef Q = QueryParser::parse(Line.c_str(), QS); + QueryRef Q = QueryParser::parse(llvm::StringRef(Line.c_str()), QS); if (!Q->run(llvm::outs(), QS)) return 1; } Index: clang-tools-extra/clang-tidy/ClangTidy.cpp =================================================================== --- clang-tools-extra/clang-tidy/ClangTidy.cpp +++ clang-tools-extra/clang-tidy/ClangTidy.cpp @@ -71,7 +71,7 @@ void FlushDiagnosticsImpl(std::vector &Diags, FilesMade *filesMade) override { for (const ento::PathDiagnostic *PD : Diags) { - SmallString<64> CheckName(AnalyzerCheckNamePrefix); + SmallString<64> CheckName((StringRef(AnalyzerCheckNamePrefix))); CheckName += PD->getCheckName(); Context.diag(CheckName, PD->getLocation().asLocation(), PD->getShortDescription()) Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp +++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp @@ -387,9 +387,10 @@ DiagnosticBuilder Diag = diag(Ctor ? Ctor->getLocStart() : ClassDecl.getLocation(), - IsUnion - ? "union constructor should initialize one of these fields: %0" - : "constructor does not initialize these fields: %0") + llvm::StringRef( + IsUnion ? "union constructor should initialize one of these " + "fields: %0" + : "constructor does not initialize these fields: %0")) << toCommaSeparatedString(OrderedFields, AllFieldsToInit); // Do not propose fixes for constructors in macros since we cannot place them @@ -468,7 +469,7 @@ Diag << FixItHint::CreateInsertion( getLocationForEndOfToken(Context, Var->getSourceRange().getEnd()), - Context.getLangOpts().CPlusPlus11 ? "{}" : " = {}"); + llvm::StringRef(Context.getLangOpts().CPlusPlus11 ? "{}" : " = {}")); } } // namespace cppcoreguidelines Index: clang-tools-extra/clang-tidy/misc/FoldInitTypeCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/misc/FoldInitTypeCheck.cpp +++ clang-tools-extra/clang-tidy/misc/FoldInitTypeCheck.cpp @@ -21,7 +21,7 @@ // We match functions of interest and bind the iterator and init value types. // Note: Right now we check only builtin types. const auto BuiltinTypeWithId = [](const char *ID) { - return hasCanonicalType(builtinType().bind(ID)); + return hasCanonicalType(builtinType().bind(llvm::StringRef(ID))); }; const auto IteratorWithValueType = [&BuiltinTypeWithId](const char *ID) { return anyOf( Index: clang-tools-extra/clang-tidy/misc/NonCopyableObjects.cpp =================================================================== --- clang-tools-extra/clang-tidy/misc/NonCopyableObjects.cpp +++ clang-tools-extra/clang-tidy/misc/NonCopyableObjects.cpp @@ -23,22 +23,14 @@ // users can add their own elements to the list. However, it may require some // extra thought since POSIX types and FILE types are usable in different ways. bool isPOSIXTypeName(StringRef ClassName) { - static const char *const TypeNames[] = { - "::pthread_cond_t", - "::pthread_mutex_t", - "pthread_cond_t", - "pthread_mutex_t" - }; + static const StringRef TypeNames[] = {"::pthread_cond_t", "::pthread_mutex_t", + "pthread_cond_t", "pthread_mutex_t"}; return std::binary_search(std::begin(TypeNames), std::end(TypeNames), ClassName); } bool isFILETypeName(StringRef ClassName) { - static const char *const TypeNames[] = { - "::FILE", - "FILE", - "std::FILE" - }; + static const StringRef TypeNames[] = {"::FILE", "FILE", "std::FILE"}; return std::binary_search(std::begin(TypeNames), std::end(TypeNames), ClassName); } Index: clang-tools-extra/clang-tidy/misc/StringIntegerAssignmentCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/misc/StringIntegerAssignmentCheck.cpp +++ clang-tools-extra/clang-tidy/misc/StringIntegerAssignmentCheck.cpp @@ -64,19 +64,22 @@ SourceLocation EndLoc = Lexer::getLocForEndOfToken( Argument->getLocEnd(), 0, *Result.SourceManager, getLangOpts()); if (IsOneDigit) { - Diag << FixItHint::CreateInsertion(Loc, IsWideCharType ? "L'" : "'") + Diag << FixItHint::CreateInsertion( + Loc, llvm::StringRef(IsWideCharType ? "L'" : "'")) << FixItHint::CreateInsertion(EndLoc, "'"); return; } if (IsLiteral) { - Diag << FixItHint::CreateInsertion(Loc, IsWideCharType ? "L\"" : "\"") + Diag << FixItHint::CreateInsertion( + Loc, llvm::StringRef(IsWideCharType ? "L\"" : "\"")) << FixItHint::CreateInsertion(EndLoc, "\""); return; } if (getLangOpts().CPlusPlus11) { - Diag << FixItHint::CreateInsertion(Loc, IsWideCharType ? "std::to_wstring(" - : "std::to_string(") + Diag << FixItHint::CreateInsertion( + Loc, llvm::StringRef(IsWideCharType ? "std::to_wstring(" + : "std::to_string(")) << FixItHint::CreateInsertion(EndLoc, ")"); } } Index: clang-tools-extra/clang-tidy/misc/ThrowByValueCatchByReferenceCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/misc/ThrowByValueCatchByReferenceCheck.cpp +++ clang-tools-extra/clang-tidy/misc/ThrowByValueCatchByReferenceCheck.cpp @@ -146,13 +146,13 @@ // We do not diagnose when catching pointer to strings since we also allow // throwing string literals. if (!PT->getPointeeType()->isAnyCharacterType()) - diag(varDecl->getLocStart(), diagMsgCatchReference); + diag(varDecl->getLocStart(), llvm::StringRef(diagMsgCatchReference)); } else if (!caughtType->isReferenceType()) { // If it's not a pointer and not a reference then it must be thrown "by // value". In this case we should emit a diagnosis message unless the type // is trivial. if (!caughtType.isTrivialType(context)) - diag(varDecl->getLocStart(), diagMsgCatchReference); + diag(varDecl->getLocStart(), llvm::StringRef(diagMsgCatchReference)); } } Index: clang-tools-extra/clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp +++ clang-tools-extra/clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp @@ -76,8 +76,8 @@ const auto *Method = Result.Nodes.getNodeAs("method"); for (const auto &Message : Messages) { - if (Result.Nodes.getNodeAs(Message[0])) - diag(Method->getLocStart(), Message[1]) + if (Result.Nodes.getNodeAs(llvm::StringRef(Message[0]))) + diag(Method->getLocStart(), llvm::StringRef(Message[1])) << Method->getParent()->getName() << (Method->isConst() ? "const" : "virtual"); } Index: clang-tools-extra/clang-tidy/misc/UnusedRAIICheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/misc/UnusedRAIICheck.cpp +++ clang-tools-extra/clang-tidy/misc/UnusedRAIICheck.cpp @@ -73,7 +73,7 @@ if (TOE->getNumArgs() == 0) { D << FixItHint::CreateReplacement( CharSourceRange::getTokenRange(TOE->getParenOrBraceRange()), - Replacement); + llvm::StringRef(Replacement)); return; } @@ -86,7 +86,7 @@ D << FixItHint::CreateInsertion( Lexer::getLocForEndOfToken(TL->getLocEnd(), 0, *Result.SourceManager, getLangOpts()), - Replacement); + llvm::StringRef(Replacement)); } } // namespace misc Index: clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp +++ clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp @@ -298,8 +298,8 @@ if (!Member) return nullptr; StringRef Name = Member->getMemberDecl()->getName(); - StringRef TargetName = IsBegin ? "begin" : "end"; - StringRef ConstTargetName = IsBegin ? "cbegin" : "cend"; + StringRef TargetName = llvm::StringRef(IsBegin ? "begin" : "end"); + StringRef ConstTargetName = llvm::StringRef(IsBegin ? "cbegin" : "cend"); if (Name != TargetName && Name != ConstTargetName) return nullptr; @@ -625,7 +625,8 @@ } } - StringRef MaybeDereference = Descriptor.ContainerNeedsDereference ? "*" : ""; + StringRef MaybeDereference = + llvm::StringRef(Descriptor.ContainerNeedsDereference ? "*" : ""); std::string TypeString = Type.getAsString(getLangOpts()); std::string Range = ("(" + TypeString + " " + VarName + " : " + MaybeDereference + Descriptor.ContainerString + ")") Index: clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp +++ clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp @@ -22,8 +22,8 @@ MakeSharedCheck::getSmartPointerTypeMatcher() const { return qualType(hasDeclaration(classTemplateSpecializationDecl( matchesName("::std::shared_ptr"), templateArgumentCountIs(1), - hasTemplateArgument( - 0, templateArgument(refersToType(qualType().bind(PointerType))))))); + hasTemplateArgument(0, templateArgument(refersToType( + qualType().bind(StringRef(PointerType)))))))); } } // namespace modernize Index: clang-tools-extra/clang-tidy/modernize/MakeUniqueCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/modernize/MakeUniqueCheck.cpp +++ clang-tools-extra/clang-tidy/modernize/MakeUniqueCheck.cpp @@ -23,16 +23,17 @@ MakeUniqueCheck::getSmartPointerTypeMatcher() const { return qualType(hasDeclaration(classTemplateSpecializationDecl( matchesName("::std::unique_ptr"), templateArgumentCountIs(2), + hasTemplateArgument(0, templateArgument(refersToType( + qualType().bind(StringRef(PointerType))))), hasTemplateArgument( - 0, templateArgument(refersToType(qualType().bind(PointerType)))), - hasTemplateArgument( - 1, templateArgument(refersToType( - qualType(hasDeclaration(classTemplateSpecializationDecl( - matchesName("::std::default_delete"), - templateArgumentCountIs(1), - hasTemplateArgument( - 0, templateArgument(refersToType(qualType( - equalsBoundNode(PointerType)))))))))))))); + 1, + templateArgument(refersToType( + qualType(hasDeclaration(classTemplateSpecializationDecl( + matchesName("::std::default_delete"), + templateArgumentCountIs(1), + hasTemplateArgument( + 0, templateArgument(refersToType(qualType(equalsBoundNode( + StringRef(PointerType))))))))))))))); } } // namespace modernize Index: clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp +++ clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp @@ -182,8 +182,9 @@ const TypedefNameDecl *TypedefName) { if (protoTypeHasNoParms(TypedefName->getUnderlyingType())) { removeVoidArgumentTokens(Result, TypedefName->getSourceRange(), - isa(TypedefName) ? "typedef" - : "type alias"); + llvm::StringRef(isa(TypedefName) + ? "typedef" + : "type alias")); } } Index: clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp +++ clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp @@ -373,7 +373,8 @@ // Space after 'auto' to handle cases where the '*' in the pointer type is // next to the identifier. This avoids changing 'int *p' into 'autop'. - Diag << FixItHint::CreateReplacement(Range, RemoveStars ? "auto " : "auto") + Diag << FixItHint::CreateReplacement( + Range, llvm::StringRef(RemoveStars ? "auto " : "auto")) << StarRemovals; } Index: clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp +++ clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp @@ -58,7 +58,8 @@ if (!Expression->getLocStart().isMacroID()) Diag << FixItHint::CreateReplacement( - Expression->getSourceRange(), LiteralBooleanValue ? "true" : "false"); + Expression->getSourceRange(), + llvm::StringRef(LiteralBooleanValue ? "true" : "false")); } } // namespace modernize Index: clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp +++ clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp @@ -22,10 +22,11 @@ UseEmplaceCheck::UseEmplaceCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), - ContainersWithPushBack(utils::options::parseStringList(Options.get( - "ContainersWithPushBack", DefaultContainersWithPushBack))), - SmartPointers(utils::options::parseStringList( - Options.get("SmartPointers", DefaultSmartPointers))) {} + ContainersWithPushBack(utils::options::parseStringList( + Options.get("ContainersWithPushBack", + llvm::StringRef(DefaultContainersWithPushBack)))), + SmartPointers(utils::options::parseStringList(Options.get( + "SmartPointers", llvm::StringRef(DefaultSmartPointers)))) {} void UseEmplaceCheck::registerMatchers(MatchFinder *Finder) { if (!getLangOpts().CPlusPlus11) Index: clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp +++ clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp @@ -65,7 +65,7 @@ SourceLocation PreviousLocation = StartLoc.getLocWithOffset(-1); bool NeedsSpace = isAlphanumeric(*SM.getCharacterData(PreviousLocation)); Check.diag(Range.getBegin(), "use nullptr") << FixItHint::CreateReplacement( - Range, NeedsSpace ? " nullptr" : "nullptr"); + Range, llvm::StringRef(NeedsSpace ? " nullptr" : "nullptr")); } /// \brief Returns the name of the outermost macro. Index: clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp +++ clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp @@ -89,11 +89,11 @@ } else if (KeywordCount == 0) { Message = "annotate this function with 'override' or (rarely) 'final'"; } else { - StringRef Redundant = + StringRef Redundant = llvm::StringRef( HasVirtual ? (HasOverride && HasFinal ? "'virtual' and 'override' are" : "'virtual' is") - : "'override' is"; - StringRef Correct = HasFinal ? "'final'" : "'override'"; + : "'override' is"); + StringRef Correct = llvm::StringRef(HasFinal ? "'final'" : "'override'"); Message = (llvm::Twine(Redundant) + " redundant since the function is already declared " + Correct) Index: clang-tools-extra/clang-tidy/performance/InefficientStringConcatenationCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/performance/InefficientStringConcatenationCheck.cpp +++ clang-tools-extra/clang-tidy/performance/InefficientStringConcatenationCheck.cpp @@ -76,9 +76,9 @@ "strings; consider using 'operator+=' or 'string::append()' instead"; if (LhsStr) - diag(LhsStr->getExprLoc(), DiagMsg); + diag(LhsStr->getExprLoc(), llvm::StringRef(DiagMsg)); else if (PlusOperator) - diag(PlusOperator->getExprLoc(), DiagMsg); + diag(PlusOperator->getExprLoc(), llvm::StringRef(DiagMsg)); } } // namespace performance Index: clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp =================================================================== --- clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp +++ clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp @@ -118,12 +118,14 @@ auto Diagnostic = diag(Var.getLocation(), - IsConstQualified ? "the const qualified variable %0 is " - "copy-constructed from a const reference; " - "consider making it a const reference" - : "the variable %0 is copy-constructed from a " - "const reference but is only used as const " - "reference; consider making it a const reference") + llvm::StringRef( + IsConstQualified + ? "the const qualified variable %0 is " + "copy-constructed from a const reference; " + "consider making it a const reference" + : "the variable %0 is copy-constructed from a " + "const reference but is only used as const " + "reference; consider making it a const reference")) << &Var; if (IssueFix) recordFixes(Var, Context, Diagnostic); Index: clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp +++ clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp @@ -109,15 +109,16 @@ } } - auto Diag = - diag(Param->getLocation(), - IsConstQualified ? "the const qualified parameter %0 is " - "copied for each invocation; consider " - "making it a reference" - : "the parameter %0 is copied for each " - "invocation but only used as a const reference; " - "consider making it a const reference") - << paramNameOrIndex(Param->getName(), Index); + auto Diag = diag(Param->getLocation(), + llvm::StringRef( + IsConstQualified + ? "the const qualified parameter %0 is " + "copied for each invocation; consider " + "making it a reference" + : "the parameter %0 is copied for each " + "invocation but only used as a const reference; " + "consider making it a const reference")) + << paramNameOrIndex(Param->getName(), Index); // Do not propose fixes in macros since we cannot place them correctly, or if // function is virtual as it might break overrides. const auto *Method = llvm::dyn_cast(Function); Index: clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp +++ clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp @@ -37,7 +37,7 @@ SourceLocation ElseLoc = If->getElseLoc(); std::string ControlFlowInterruptor; for (const auto *BindingName : {"return", "continue", "break", "throw"}) - if (Result.Nodes.getNodeAs(BindingName)) + if (Result.Nodes.getNodeAs(llvm::StringRef(BindingName))) ControlFlowInterruptor = BindingName; DiagnosticBuilder Diag = diag(ElseLoc, "do not use 'else' after '%0'") Index: clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp +++ clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp @@ -202,7 +202,7 @@ for (size_t i = 0; i < SK_Count; ++i) { Options.store(Opts, (StyleNames[i] + "Case").str(), - toString(NamingStyles[i].Case)); + llvm::StringRef(toString(NamingStyles[i].Case))); Options.store(Opts, (StyleNames[i] + "Prefix").str(), NamingStyles[i].Prefix); Options.store(Opts, (StyleNames[i] + "Suffix").str(), Index: clang-tools-extra/clang-tidy/readability/ImplicitBoolCastCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/readability/ImplicitBoolCastCheck.cpp +++ clang-tools-extra/clang-tidy/readability/ImplicitBoolCastCheck.cpp @@ -62,15 +62,17 @@ ASTContext &Context) { switch (CastExpressionKind) { case CK_IntegralToBoolean: - return CastSubExpressionType->isUnsignedIntegerType() ? "0u" : "0"; + return llvm::StringRef( + CastSubExpressionType->isUnsignedIntegerType() ? "0u" : "0"); case CK_FloatingToBoolean: - return Context.hasSameType(CastSubExpressionType, Context.FloatTy) ? "0.0f" - : "0.0"; + return llvm::StringRef( + Context.hasSameType(CastSubExpressionType, Context.FloatTy) ? "0.0f" + : "0.0"); case CK_PointerToBoolean: case CK_MemberPointerToBoolean: // Fall-through on purpose. - return Context.getLangOpts().CPlusPlus11 ? "nullptr" : "0"; + return llvm::StringRef(Context.getLangOpts().CPlusPlus11 ? "nullptr" : "0"); default: llvm_unreachable("Unexpected cast kind"); @@ -183,17 +185,18 @@ } if (const auto *IntLit = llvm::dyn_cast(Expression)) { - return (IntLit->getValue() == 0) ? "false" : "true"; + return llvm::StringRef((IntLit->getValue() == 0) ? "false" : "true"); } if (const auto *FloatLit = llvm::dyn_cast(Expression)) { llvm::APFloat FloatLitAbsValue = FloatLit->getValue(); FloatLitAbsValue.clearSign(); - return (FloatLitAbsValue.bitcastToAPInt() == 0) ? "false" : "true"; + return llvm::StringRef((FloatLitAbsValue.bitcastToAPInt() == 0) ? "false" + : "true"); } if (const auto *CharLit = llvm::dyn_cast(Expression)) { - return (CharLit->getValue() == 0) ? "false" : "true"; + return llvm::StringRef((CharLit->getValue() == 0) ? "false" : "true"); } if (llvm::isa(Expression->IgnoreCasts())) { @@ -253,17 +256,19 @@ if (DestinationType->isFloatingType()) { if (BoolLiteralExpression->getValue() == true) { - return Context.hasSameType(DestinationType, Context.FloatTy) ? "1.0f" - : "1.0"; + return llvm::StringRef( + Context.hasSameType(DestinationType, Context.FloatTy) ? "1.0f" + : "1.0"); } - return Context.hasSameType(DestinationType, Context.FloatTy) ? "0.0f" - : "0.0"; + return llvm::StringRef( + Context.hasSameType(DestinationType, Context.FloatTy) ? "0.0f" : "0.0"); } if (BoolLiteralExpression->getValue() == true) { - return DestinationType->isUnsignedIntegerType() ? "1u" : "1"; + return llvm::StringRef(DestinationType->isUnsignedIntegerType() ? "1u" + : "1"); } - return DestinationType->isUnsignedIntegerType() ? "0u" : "0"; + return llvm::StringRef(DestinationType->isUnsignedIntegerType() ? "0u" : "0"); } void addFixItHintsForLiteralCastFromBool(DiagnosticBuilder &Diagnostic, Index: clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp +++ clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp @@ -89,7 +89,8 @@ StmtRange.getEnd(), tok::semi, SM, getLangOpts(), /*SkipTrailingWhitespaceAndNewLine=*/true)); - diag(StmtRange.getBegin(), Diag) << FixItHint::CreateRemoval(RemovedRange); + diag(StmtRange.getBegin(), llvm::StringRef(Diag)) + << FixItHint::CreateRemoval(RemovedRange); } } // namespace readability Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp =================================================================== --- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp +++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp @@ -611,7 +611,8 @@ void SimplifyBooleanExprCheck::replaceWithReturnCondition( const MatchFinder::MatchResult &Result, const IfStmt *If, bool Negated) { - StringRef Terminator = isa(If->getElse()) ? ";" : ""; + StringRef Terminator = + llvm::StringRef(isa(If->getElse()) ? ";" : ""); std::string Condition = replacementExpression(Result, Negated, If->getCond()); std::string Replacement = ("return " + Condition + Terminator).str(); SourceLocation Start = @@ -666,7 +667,8 @@ SourceRange Range = IfAssign->getSourceRange(); StringRef VariableName = getText(Result, *Result.Nodes.getNodeAs(IfAssignVariableId)); - StringRef Terminator = isa(IfAssign->getElse()) ? ";" : ""; + StringRef Terminator = + llvm::StringRef(isa(IfAssign->getElse()) ? ";" : ""); std::string Condition = replacementExpression(Result, Negated, IfAssign->getCond()); std::string Replacement = Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp =================================================================== --- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp +++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp @@ -26,7 +26,7 @@ static cl::OptionCategory ClangTidyCategory("clang-tidy options"); -static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); +static cl::extrahelp CommonHelp((StringRef(CommonOptionsParser::HelpMessage))); static cl::extrahelp ClangTidyHelp(R"( Configuration files: clang-tidy attempts to read configuration for each source file from a @@ -411,7 +411,7 @@ printProfileData(Profile, llvm::errs()); if (WErrorCount) { - StringRef Plural = WErrorCount == 1 ? "" : "s"; + StringRef Plural = llvm::StringRef(WErrorCount == 1 ? "" : "s"); llvm::errs() << WErrorCount << " warning" << Plural << " treated as error" << Plural << "\n"; return WErrorCount; Index: clang-tools-extra/clang-tidy/utils/HeaderFileExtensionsUtils.cpp =================================================================== --- clang-tools-extra/clang-tidy/utils/HeaderFileExtensionsUtils.cpp +++ clang-tools-extra/clang-tidy/utils/HeaderFileExtensionsUtils.cpp @@ -27,7 +27,7 @@ SourceLocation Loc, SourceManager &SM, const HeaderFileExtensionsSet &HeaderFileExtensions) { PresumedLoc PresumedLocation = SM.getPresumedLoc(Loc); - return isHeaderFileExtension(PresumedLocation.getFilename(), + return isHeaderFileExtension(llvm::StringRef(PresumedLocation.getFilename()), HeaderFileExtensions); } Index: clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp =================================================================== --- clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp +++ clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp @@ -16,7 +16,7 @@ namespace { -StringRef RemoveFirstSuffix(StringRef Str, ArrayRef Suffixes) { +StringRef RemoveFirstSuffix(StringRef Str, ArrayRef Suffixes) { for (StringRef Suffix : Suffixes) { if (Str.endswith(Suffix)) { return Str.substr(0, Str.size() - Suffix.size()); @@ -281,7 +281,7 @@ } StringRef IncludeSorter::toString(IncludeStyle Style) { - return Style == IS_LLVM ? "llvm" : "google"; + return llvm::StringRef(Style == IS_LLVM ? "llvm" : "google"); } } // namespace utils Index: clang-tools-extra/include-fixer/find-all-symbols/HeaderMapCollector.cpp =================================================================== --- clang-tools-extra/include-fixer/find-all-symbols/HeaderMapCollector.cpp +++ clang-tools-extra/include-fixer/find-all-symbols/HeaderMapCollector.cpp @@ -22,8 +22,8 @@ // regex header mapping. if (RegexHeaderMappingTable) { for (const auto &Entry : *RegexHeaderMappingTable) { - if (llvm::Regex(Entry.first).match(Header)) - return Entry.second; + if (llvm::Regex(llvm::StringRef(Entry.first)).match(Header)) + return llvm::StringRef(Entry.second); } } return Header; Index: clang-tools-extra/include-fixer/find-all-symbols/tool/FindAllSymbolsMain.cpp =================================================================== --- clang-tools-extra/include-fixer/find-all-symbols/tool/FindAllSymbolsMain.cpp +++ clang-tools-extra/include-fixer/find-all-symbols/tool/FindAllSymbolsMain.cpp @@ -45,7 +45,7 @@ // CommonOptionsParser declares HelpMessage with a description of the common // command-line options related to the compilation database and input files. // It's nice to have this help message in all tools. -static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); +static cl::extrahelp CommonHelp((StringRef(CommonOptionsParser::HelpMessage))); // A help message for this specific tool can be added afterwards. static cl::extrahelp MoreHelp("\nMore help text..."); Index: clang-tools-extra/modularize/Modularize.cpp =================================================================== --- clang-tools-extra/modularize/Modularize.cpp +++ clang-tools-extra/modularize/Modularize.cpp @@ -813,7 +813,7 @@ Argv0 = Argv[0]; // Save program arguments for use in module.modulemap comment. - CommandLine = sys::path::stem(sys::path::filename(Argv0)); + CommandLine = sys::path::stem(sys::path::filename(llvm::StringRef(Argv0))); for (int ArgIndex = 1; ArgIndex < Argc; ArgIndex++) { CommandLine.append(" "); CommandLine.append(Argv[ArgIndex]); Index: clang-tools-extra/modularize/ModuleAssistant.cpp =================================================================== --- clang-tools-extra/modularize/ModuleAssistant.cpp +++ clang-tools-extra/modularize/ModuleAssistant.cpp @@ -149,7 +149,7 @@ ensureNoCollisionWithReservedName(llvm::StringRef MightBeReservedName) { std::string SafeName = MightBeReservedName; for (int Index = 0; ReservedNames[Index] != nullptr; ++Index) { - if (MightBeReservedName == ReservedNames[Index]) { + if (MightBeReservedName == llvm::StringRef(ReservedNames[Index])) { SafeName.insert(0, "_"); break; } Index: clang-tools-extra/modularize/PreprocessorTracker.cpp =================================================================== --- clang-tools-extra/modularize/PreprocessorTracker.cpp +++ clang-tools-extra/modularize/PreprocessorTracker.cpp @@ -1363,7 +1363,8 @@ PPTracker.addMacroExpansionInstance( PP, PPTracker.getCurrentHeaderHandle(), Loc, (MI ? MI->getDefinitionLoc() : Loc), II, Unexpanded, - (MI ? "true" : "false"), PPTracker.getCurrentInclusionPathHandle()); + llvm::StringRef((MI ? "true" : "false")), + PPTracker.getCurrentInclusionPathHandle()); } void PreprocessorCallbacks::If(clang::SourceLocation Loc, Index: clang-tools-extra/pp-trace/PPCallbacksTracker.cpp =================================================================== --- clang-tools-extra/pp-trace/PPCallbacksTracker.cpp +++ clang-tools-extra/pp-trace/PPCallbacksTracker.cpp @@ -411,7 +411,7 @@ DisableTrace = Ignore.count(std::string(Name)); if (DisableTrace) return; - CallbackCalls.push_back(CallbackCall(Name)); + CallbackCalls.push_back(CallbackCall(llvm::StringRef(Name))); } // Append a bool argument to the top trace item. @@ -431,7 +431,8 @@ void PPCallbacksTracker::appendArgument(const char *Name, const char *Value) { if (DisableTrace) return; - CallbackCalls.back().Arguments.push_back(Argument(Name, Value)); + CallbackCalls.back().Arguments.push_back( + Argument(llvm::StringRef(Name), llvm::StringRef(Value))); } // Append a string object argument to the top trace item. Index: clang-tools-extra/tool-template/ToolTemplate.cpp =================================================================== --- clang-tools-extra/tool-template/ToolTemplate.cpp +++ clang-tools-extra/tool-template/ToolTemplate.cpp @@ -71,11 +71,11 @@ } // end anonymous namespace // Set up the command line options -static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); +static cl::extrahelp CommonHelp((StringRef(CommonOptionsParser::HelpMessage))); static cl::OptionCategory ToolTemplateCategory("tool-template options"); int main(int argc, const char **argv) { - llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); + llvm::sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0])); CommonOptionsParser OptionsParser(argc, argv, ToolTemplateCategory); RefactoringTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList()); Index: clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp =================================================================== --- clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp +++ clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp @@ -152,9 +152,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_input2.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_input2.cc")); } TEST(IncludeInserterTest, InsertMultipleIncludesAndDeduplicate) { @@ -183,9 +184,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_input2.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_input2.cc")); } TEST(IncludeInserterTest, InsertBeforeFirstNonSystemInclude) { @@ -213,9 +215,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_input2.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_input2.cc")); } TEST(IncludeInserterTest, InsertBetweenNonSystemIncludes) { @@ -245,9 +248,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_input2.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_input2.cc")); } TEST(IncludeInserterTest, NonSystemIncludeAlreadyIncluded) { @@ -265,8 +269,8 @@ int a = 0; })"; EXPECT_EQ(PreCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_input2.cc")); + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_input2.cc")); } TEST(IncludeInserterTest, InsertNonSystemIncludeAfterLastCXXSystemInclude) { @@ -291,9 +295,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_header.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_header.cc")); } TEST(IncludeInserterTest, InsertNonSystemIncludeAfterMainFileInclude) { @@ -312,9 +317,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_header.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_header.cc")); } TEST(IncludeInserterTest, InsertCXXSystemIncludeAfterLastCXXSystemInclude) { @@ -342,9 +348,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_header.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_header.cc")); } TEST(IncludeInserterTest, InsertCXXSystemIncludeBeforeFirstCXXSystemInclude) { @@ -370,9 +377,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_header.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_header.cc")); } TEST(IncludeInserterTest, InsertCXXSystemIncludeBetweenCXXSystemIncludes) { @@ -400,9 +408,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_header.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_header.cc")); } TEST(IncludeInserterTest, InsertCXXSystemIncludeAfterMainFileInclude) { @@ -425,9 +434,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_header.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_header.cc")); } TEST(IncludeInserterTest, InsertCXXSystemIncludeAfterCSystemInclude) { @@ -454,9 +464,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "clang_tidy/tests/" - "insert_includes_test_header.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "clang_tidy/tests/" + "insert_includes_test_header.cc")); } TEST(IncludeInserterTest, InsertCXXSystemIncludeBeforeNonSystemInclude) { @@ -475,9 +486,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "devtools/cymbal/clang_tidy/tests/" - "insert_includes_test_header.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "devtools/cymbal/clang_tidy/tests/" + "insert_includes_test_header.cc")); } TEST(IncludeInserterTest, InsertCSystemIncludeBeforeCXXSystemInclude) { @@ -500,9 +512,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "devtools/cymbal/clang_tidy/tests/" - "insert_includes_test_header.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "devtools/cymbal/clang_tidy/tests/" + "insert_includes_test_header.cc")); } TEST(IncludeInserterTest, InsertIncludeIfThereWasNoneBefore) { @@ -517,9 +530,10 @@ int a = 0; })"; - EXPECT_EQ(PostCode, runCheckOnCode( - PreCode, "devtools/cymbal/clang_tidy/tests/" - "insert_includes_test_header.cc")); + EXPECT_EQ(PostCode, + runCheckOnCode( + StringRef(PreCode), "devtools/cymbal/clang_tidy/tests/" + "insert_includes_test_header.cc")); } } // anonymous namespace Index: clang/examples/clang-interpreter/main.cpp =================================================================== --- clang/examples/clang-interpreter/main.cpp +++ clang/examples/clang-interpreter/main.cpp @@ -156,7 +156,8 @@ if (Clang.getHeaderSearchOpts().UseBuiltinIncludes && Clang.getHeaderSearchOpts().ResourceDir.empty()) Clang.getHeaderSearchOpts().ResourceDir = - CompilerInvocation::GetResourcesPath(argv[0], MainAddr); + CompilerInvocation::GetResourcesPath(llvm::StringRef(argv[0]), + MainAddr); // Create and execute the frontend to generate an LLVM bitcode module. std::unique_ptr Act(new EmitLLVMOnlyAction()); Index: clang/include/clang/AST/Comment.h =================================================================== --- clang/include/clang/AST/Comment.h +++ clang/include/clang/AST/Comment.h @@ -347,7 +347,7 @@ } StringRef getCommandName(const CommandTraits &Traits) const { - return Traits.getCommandInfo(getCommandID())->Name; + return StringRef(Traits.getCommandInfo(getCommandID())->Name); } SourceRange getCommandNameRange() const { @@ -658,7 +658,7 @@ } StringRef getCommandName(const CommandTraits &Traits) const { - return Traits.getCommandInfo(getCommandID())->Name; + return StringRef(Traits.getCommandInfo(getCommandID())->Name); } SourceLocation getCommandNameBeginLoc() const { Index: clang/include/clang/AST/Decl.h =================================================================== --- clang/include/clang/AST/Decl.h +++ clang/include/clang/AST/Decl.h @@ -131,7 +131,7 @@ PragmaMSCommentKind getCommentKind() const { return CommentKind; } - StringRef getArg() const { return getTrailingObjects(); } + StringRef getArg() const { return StringRef(getTrailingObjects()); } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return classofKind(D->getKind()); } @@ -163,8 +163,10 @@ static PragmaDetectMismatchDecl * CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize); - StringRef getName() const { return getTrailingObjects(); } - StringRef getValue() const { return getTrailingObjects() + ValueStart; } + StringRef getName() const { return StringRef(getTrailingObjects()); } + StringRef getValue() const { + return StringRef(getTrailingObjects() + ValueStart); + } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return classofKind(D->getKind()); } Index: clang/include/clang/Basic/SourceManager.h =================================================================== --- clang/include/clang/Basic/SourceManager.h +++ clang/include/clang/Basic/SourceManager.h @@ -996,7 +996,7 @@ /// \brief Return the filename of the file containing a SourceLocation. StringRef getFilename(SourceLocation SpellingLoc) const { if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc))) - return F->getName(); + return StringRef(F->getName()); return StringRef(); } @@ -1045,7 +1045,7 @@ // Positive file IDs are in the current translation unit, and -1 is a // placeholder. if (FID.ID >= -1) - return std::make_pair(SourceLocation(), ""); + return std::make_pair(SourceLocation(), StringRef("")); return ExternalSLocEntries->getModuleImportLoc(FID.ID); } Index: clang/include/clang/Serialization/ASTReader.h =================================================================== --- clang/include/clang/Serialization/ASTReader.h +++ clang/include/clang/Serialization/ASTReader.h @@ -2193,7 +2193,7 @@ }; inline void PCHValidator::Error(const char *Msg) { - Reader.Error(Msg); + Reader.Error(StringRef(Msg)); } } // end namespace clang Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h =================================================================== --- clang/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h +++ clang/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h @@ -61,15 +61,17 @@ const std::string desc; void anchor() override; public: - BuiltinBug(class CheckName check, const char *name, const char *description) - : BugType(check, name, categories::LogicError), desc(description) {} + BuiltinBug(class CheckName check, StringRef name, const char *description) + : BugType(check, name, StringRef(categories::LogicError)), + desc(description) {} - BuiltinBug(const CheckerBase *checker, const char *name, + BuiltinBug(const CheckerBase *checker, StringRef name, const char *description) - : BugType(checker, name, categories::LogicError), desc(description) {} + : BugType(checker, name, StringRef(categories::LogicError)), + desc(description) {} - BuiltinBug(const CheckerBase *checker, const char *name) - : BugType(checker, name, categories::LogicError), desc(name) {} + BuiltinBug(const CheckerBase *checker, StringRef name) + : BugType(checker, name, StringRef(categories::LogicError)), desc(name) {} StringRef getDescription() const { return desc; } }; Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h =================================================================== --- clang/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h +++ clang/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h @@ -371,8 +371,8 @@ StringRef getString() const { return str; } /// Tag this PathDiagnosticPiece with the given C-string. - void setTag(const char *tag) { Tag = tag; } - + void setTag(const char *tag) { Tag = StringRef(tag); } + /// Return the opaque tag (if any) on the PathDiagnosticPiece. const void *getTag() const { return Tag.data(); } Index: clang/lib/ARCMigrate/ObjCMT.cpp =================================================================== --- clang/lib/ARCMigrate/ObjCMT.cpp +++ clang/lib/ARCMigrate/ObjCMT.cpp @@ -1190,7 +1190,7 @@ if (!IsValidIdentifier(Ctx, CGetterName)) return false; if (CGetterName[0] && isUppercase(CGetterName[0])) { - getterName = &Ctx.Idents.get(CGetterName); + getterName = &Ctx.Idents.get(llvm::StringRef(CGetterName)); SetterSelector = SelectorTable::constructSetterSelector(PP.getIdentifierTable(), PP.getSelectorTable(), @@ -1395,7 +1395,7 @@ CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1]; const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n"; edit::Commit commit(*Editor); - commit.insertBefore(FirstFD->getLocStart(), PragmaString); + commit.insertBefore(FirstFD->getLocStart(), llvm::StringRef(PragmaString)); PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n"; SourceLocation EndLoc = LastFD->getLocEnd(); // get location just past end of function location. @@ -1409,7 +1409,7 @@ if (!Failed) EndLoc = Tok.getLocation(); } - commit.insertAfterToken(EndLoc, PragmaString); + commit.insertAfterToken(EndLoc, llvm::StringRef(PragmaString)); Editor->commit(commit); FileId = FileID(); CFFunctionIBCandidates.clear(); @@ -1472,7 +1472,8 @@ if (AnnotationString) { edit::Commit commit(*Editor); - commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString); + commit.insertAfterToken(FuncDecl->getLocEnd(), + llvm::StringRef(AnnotationString)); Editor->commit(commit); } } @@ -1598,7 +1599,8 @@ if (AnnotationString) { edit::Commit commit(*Editor); - commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString); + commit.insertBefore(MethodDecl->getLocEnd(), + llvm::StringRef(AnnotationString)); Editor->commit(commit); } } Index: clang/lib/ARCMigrate/TransBlockObjCVariable.cpp =================================================================== --- clang/lib/ARCMigrate/TransBlockObjCVariable.cpp +++ clang/lib/ARCMigrate/TransBlockObjCVariable.cpp @@ -140,8 +140,8 @@ bool useWeak = canApplyWeak(Pass.Ctx, var->getType()); SourceManager &SM = Pass.Ctx.getSourceManager(); Transaction Trans(Pass.TA); - Pass.TA.replaceText(SM.getExpansionLoc(attr->getLocation()), - "__block", - useWeak ? "__weak" : "__unsafe_unretained"); + Pass.TA.replaceText( + SM.getExpansionLoc(attr->getLocation()), "__block", + llvm::StringRef(useWeak ? "__weak" : "__unsafe_unretained")); } } Index: clang/lib/ARCMigrate/TransProperties.cpp =================================================================== --- clang/lib/ARCMigrate/TransProperties.cpp +++ clang/lib/ARCMigrate/TransProperties.cpp @@ -219,7 +219,8 @@ (Pass.isGCMigration() && !hasGCWeak(props, atLoc)) ? "strong" : (canUseWeak ? "weak" : "unsafe_unretained"); - bool rewroteAttr = rewriteAttribute("assign", toWhich, atLoc); + bool rewroteAttr = + rewriteAttribute("assign", llvm::StringRef(toWhich), atLoc); if (!rewroteAttr) canUseWeak = false; @@ -230,7 +231,7 @@ const char *toWhich = (Pass.isGCMigration() && !hasGCWeak(props, atLoc)) ? "__strong " : (canUseWeak ? "__weak " : "__unsafe_unretained "); - Pass.TA.insert(I->IvarD->getLocation(), toWhich); + Pass.TA.insert(I->IvarD->getLocation(), llvm::StringRef(toWhich)); } } if (I->ImplD) @@ -246,8 +247,8 @@ bool canUseWeak = canApplyWeak(Pass.Ctx, getPropertyType(props), /*AllowOnUnknownClass=*/Pass.isGCMigration()); - bool addedAttr = addAttribute(canUseWeak ? "weak" : "unsafe_unretained", - atLoc); + bool addedAttr = addAttribute( + llvm::StringRef(canUseWeak ? "weak" : "unsafe_unretained"), atLoc); if (!addedAttr) canUseWeak = false; @@ -255,8 +256,9 @@ if (isUserDeclared(I->IvarD)) { if (I->IvarD && I->IvarD->getType().getObjCLifetime() != Qualifiers::OCL_Weak) - Pass.TA.insert(I->IvarD->getLocation(), - canUseWeak ? "__weak " : "__unsafe_unretained "); + Pass.TA.insert( + I->IvarD->getLocation(), + llvm::StringRef(canUseWeak ? "__weak " : "__unsafe_unretained ")); } if (I->ImplD) { Pass.TA.clearDiagnostic(diag::err_arc_strong_property_ownership, Index: clang/lib/ARCMigrate/Transforms.cpp =================================================================== --- clang/lib/ARCMigrate/Transforms.cpp +++ clang/lib/ARCMigrate/Transforms.cpp @@ -207,7 +207,7 @@ } StringRef trans::getNilString(MigrationPass &Pass) { - return Pass.SemaRef.PP.isMacroDefined("nil") ? "nil" : "0"; + return llvm::StringRef(Pass.SemaRef.PP.isMacroDefined("nil") ? "nil" : "0"); } namespace { Index: clang/lib/AST/ASTContext.cpp =================================================================== --- clang/lib/AST/ASTContext.cpp +++ clang/lib/AST/ASTContext.cpp @@ -5173,14 +5173,12 @@ // Create fields for (unsigned i = 0; i < 4; ++i) { - FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl, - SourceLocation(), - SourceLocation(), - &Idents.get(FieldNames[i]), - FieldTypes[i], /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, - /*Mutable=*/false, - ICIS_NoInit); + FieldDecl *Field = FieldDecl::Create( + *this, CFConstantStringTagDecl, SourceLocation(), SourceLocation(), + &Idents.get(llvm::StringRef(FieldNames[i])), FieldTypes[i], + /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, + /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); CFConstantStringTagDecl->addDecl(Field); } @@ -5246,10 +5244,11 @@ }; for (size_t i = 0; i < 2; ++i) { - FieldDecl *Field = FieldDecl::Create( - *this, RD, SourceLocation(), SourceLocation(), - &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); + FieldDecl *Field = + FieldDecl::Create(*this, RD, SourceLocation(), SourceLocation(), + &Idents.get(llvm::StringRef(FieldNames[i])), + FieldTypes[i], /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); RD->addDecl(Field); } @@ -5285,11 +5284,12 @@ }; for (size_t i = 0; i < 4; ++i) { - FieldDecl *Field = FieldDecl::Create( - *this, RD, SourceLocation(), SourceLocation(), - &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, - /*Mutable=*/false, ICIS_NoInit); + FieldDecl *Field = + FieldDecl::Create(*this, RD, SourceLocation(), SourceLocation(), + &Idents.get(llvm::StringRef(FieldNames[i])), + FieldTypes[i], /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, + /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); RD->addDecl(Field); } @@ -6495,15 +6495,12 @@ // Create fields for (unsigned i = 0; i < NumFields; ++i) { - FieldDecl *Field = FieldDecl::Create(const_cast(*Context), - VaListTagDecl, - SourceLocation(), - SourceLocation(), - &Context->Idents.get(FieldNames[i]), - FieldTypes[i], /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, - /*Mutable=*/false, - ICIS_NoInit); + FieldDecl *Field = FieldDecl::Create( + const_cast(*Context), VaListTagDecl, SourceLocation(), + SourceLocation(), &Context->Idents.get(llvm::StringRef(FieldNames[i])), + FieldTypes[i], /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, + /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } @@ -6548,14 +6545,12 @@ // Create fields for (unsigned i = 0; i < NumFields; ++i) { - FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, - SourceLocation(), - SourceLocation(), - &Context->Idents.get(FieldNames[i]), - FieldTypes[i], /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, - /*Mutable=*/false, - ICIS_NoInit); + FieldDecl *Field = FieldDecl::Create( + *Context, VaListTagDecl, SourceLocation(), SourceLocation(), + &Context->Idents.get(llvm::StringRef(FieldNames[i])), FieldTypes[i], + /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, + /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } @@ -6607,15 +6602,12 @@ // Create fields for (unsigned i = 0; i < NumFields; ++i) { - FieldDecl *Field = FieldDecl::Create(const_cast(*Context), - VaListTagDecl, - SourceLocation(), - SourceLocation(), - &Context->Idents.get(FieldNames[i]), - FieldTypes[i], /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, - /*Mutable=*/false, - ICIS_NoInit); + FieldDecl *Field = FieldDecl::Create( + const_cast(*Context), VaListTagDecl, SourceLocation(), + SourceLocation(), &Context->Idents.get(llvm::StringRef(FieldNames[i])), + FieldTypes[i], /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, + /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } @@ -6710,15 +6702,12 @@ // Create fields for (unsigned i = 0; i < NumFields; ++i) { - FieldDecl *Field = FieldDecl::Create(const_cast(*Context), - VaListTagDecl, - SourceLocation(), - SourceLocation(), - &Context->Idents.get(FieldNames[i]), - FieldTypes[i], /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, - /*Mutable=*/false, - ICIS_NoInit); + FieldDecl *Field = FieldDecl::Create( + const_cast(*Context), VaListTagDecl, SourceLocation(), + SourceLocation(), &Context->Idents.get(llvm::StringRef(FieldNames[i])), + FieldTypes[i], /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, + /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } Index: clang/lib/AST/ASTTypeTraits.cpp =================================================================== --- clang/lib/AST/ASTTypeTraits.cpp +++ clang/lib/AST/ASTTypeTraits.cpp @@ -57,7 +57,9 @@ return Derived == Base; } -StringRef ASTNodeKind::asStringRef() const { return AllKindInfo[KindId].Name; } +StringRef ASTNodeKind::asStringRef() const { + return llvm::StringRef(AllKindInfo[KindId].Name); +} ASTNodeKind ASTNodeKind::getMostDerivedType(ASTNodeKind Kind1, ASTNodeKind Kind2) { Index: clang/lib/AST/CommentCommandTraits.cpp =================================================================== --- clang/lib/AST/CommentCommandTraits.cpp +++ clang/lib/AST/CommentCommandTraits.cpp @@ -57,7 +57,7 @@ SmallVector BestCommand; auto ConsiderCorrection = [&](const CommandInfo *Command) { - StringRef Name = Command->Name; + StringRef Name = llvm::StringRef(Command->Name); unsigned MinPossibleEditDistance = abs((int)Name.size() - (int)Typo.size()); if (MinPossibleEditDistance <= BestEditDistance) { @@ -123,7 +123,7 @@ const CommandInfo *CommandTraits::getRegisteredCommandInfo( StringRef Name) const { for (unsigned i = 0, e = RegisteredCommands.size(); i != e; ++i) { - if (RegisteredCommands[i]->Name == Name) + if (llvm::StringRef(RegisteredCommands[i]->Name) == Name) return RegisteredCommands[i]; } return nullptr; Index: clang/lib/AST/CommentLexer.cpp =================================================================== --- clang/lib/AST/CommentLexer.cpp +++ clang/lib/AST/CommentLexer.cpp @@ -376,7 +376,7 @@ const CommandInfo *Info = Traits.getCommandInfoOrNULL(CommandName); if (!Info) { if ((Info = Traits.getTypoCorrectCommandInfo(CommandName))) { - StringRef CorrectedName = Info->Name; + StringRef CorrectedName = llvm::StringRef(Info->Name); SourceLocation Loc = getSourceLocation(BufferPtr); SourceRange CommandRange(Loc.getLocWithOffset(1), getSourceLocation(TokenPtr)); @@ -453,7 +453,7 @@ VerbatimBlockEndCommandName.clear(); VerbatimBlockEndCommandName.append(Marker == '\\' ? "\\" : "@"); - VerbatimBlockEndCommandName.append(Info->EndCommandName); + VerbatimBlockEndCommandName.append(llvm::StringRef(Info->EndCommandName)); formTokenWithChars(T, TextBegin, tok::verbatim_block_begin); T.setVerbatimBlockID(Info->getID()); Index: clang/lib/AST/CommentParser.cpp =================================================================== --- clang/lib/AST/CommentParser.cpp +++ clang/lib/AST/CommentParser.cpp @@ -687,7 +687,7 @@ if (Tok.is(tok::verbatim_block_end)) { const CommandInfo *Info = Traits.getCommandInfo(Tok.getVerbatimBlockID()); S.actOnVerbatimBlockFinish(VB, Tok.getLocation(), - Info->Name, + llvm::StringRef(Info->Name), S.copyArray(llvm::makeArrayRef(Lines))); consumeToken(); } else { Index: clang/lib/AST/CommentSema.cpp =================================================================== --- clang/lib/AST/CommentSema.cpp +++ clang/lib/AST/CommentSema.cpp @@ -244,7 +244,8 @@ const char *FixedName = ParamCommandComment::getDirectionAsString( (ParamCommandComment::PassDirection)Direction); Diag(ArgLocBegin, diag::warn_doc_param_spaces_in_direction) - << ArgRange << FixItHint::CreateReplacement(ArgRange, FixedName); + << ArgRange + << FixItHint::CreateReplacement(ArgRange, llvm::StringRef(FixedName)); } else { Diag(ArgLocBegin, diag::warn_doc_param_invalid_direction) << ArgRange; Direction = ParamCommandComment::In; // Sane fall back. @@ -365,7 +366,8 @@ SourceLocation CommandLocEnd, unsigned CommandID) { ArrayRef Args; - StringRef CommandName = Traits.getCommandInfo(CommandID)->Name; + StringRef CommandName = + llvm::StringRef(Traits.getCommandInfo(CommandID)->Name); return new (Allocator) InlineCommandComment( CommandLocBegin, CommandLocEnd, @@ -384,7 +386,8 @@ Argument *A = new (Allocator) Argument(SourceRange(ArgLocBegin, ArgLocEnd), Arg); - StringRef CommandName = Traits.getCommandInfo(CommandID)->Name; + StringRef CommandName = + llvm::StringRef(Traits.getCommandInfo(CommandID)->Name); return new (Allocator) InlineCommandComment( CommandLocBegin, @@ -419,7 +422,8 @@ VerbatimBlockComment *Sema::actOnVerbatimBlockStart(SourceLocation Loc, unsigned CommandID) { - StringRef CommandName = Traits.getCommandInfo(CommandID)->Name; + StringRef CommandName = + llvm::StringRef(Traits.getCommandInfo(CommandID)->Name); return new (Allocator) VerbatimBlockComment( Loc, Loc.getLocWithOffset(1 + CommandName.size()), Index: clang/lib/AST/Decl.cpp =================================================================== --- clang/lib/AST/Decl.cpp +++ clang/lib/AST/Decl.cpp @@ -4088,7 +4088,7 @@ char *Buffer = new (getASTContext(), 1) char[Name.size() + 1]; memcpy(Buffer, Name.data(), Name.size()); Buffer[Name.size()] = '\0'; - MSAsmName = Buffer; + MSAsmName = llvm::StringRef(Buffer); } void ValueDecl::anchor() { } Index: clang/lib/AST/ItaniumMangle.cpp =================================================================== --- clang/lib/AST/ItaniumMangle.cpp +++ clang/lib/AST/ItaniumMangle.cpp @@ -1132,7 +1132,8 @@ Out << "sr"; } - if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : "")) + if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), + llvm::StringRef(recursive ? "N" : ""))) return; break; @@ -4310,7 +4311,7 @@ if (!isCharType(TemplateArgs[0].getAsType())) return false; - return SD->getIdentifier()->getName() == Name; + return SD->getIdentifier()->getName() == llvm::StringRef(Name); } template Index: clang/lib/AST/MicrosoftMangle.cpp =================================================================== --- clang/lib/AST/MicrosoftMangle.cpp +++ clang/lib/AST/MicrosoftMangle.cpp @@ -1887,7 +1887,8 @@ Out << '?'; assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType && "shouldn't need to mangle __auto_type!"); - mangleSourceName(AT->isDecltypeAuto() ? "" : ""); + mangleSourceName( + llvm::StringRef(AT->isDecltypeAuto() ? "" : "")); Out << '@'; } else if (IsInLambda) { Out << '@'; Index: clang/lib/AST/NSAPI.cpp =================================================================== --- clang/lib/AST/NSAPI.cpp +++ clang/lib/AST/NSAPI.cpp @@ -35,7 +35,7 @@ }; if (!ClassIds[K]) - return (ClassIds[K] = &Ctx.Idents.get(ClassName[K])); + return (ClassIds[K] = &Ctx.Idents.get(llvm::StringRef(ClassName[K]))); return ClassIds[K]; } @@ -371,7 +371,8 @@ } if (Sels[MK].isNull()) - Sels[MK] = Ctx.Selectors.getUnarySelector(&Ctx.Idents.get(Names[MK])); + Sels[MK] = Ctx.Selectors.getUnarySelector( + &Ctx.Idents.get(llvm::StringRef(Names[MK]))); return Sels[MK]; } Index: clang/lib/AST/Type.cpp =================================================================== --- clang/lib/AST/Type.cpp +++ clang/lib/AST/Type.cpp @@ -2550,7 +2550,7 @@ case Void: return "void"; case Bool: - return Policy.Bool ? "bool" : "_Bool"; + return llvm::StringRef(Policy.Bool ? "bool" : "_Bool"); case Char_S: return "char"; case Char_U: @@ -2580,7 +2580,7 @@ case UInt128: return "unsigned __int128"; case Half: - return Policy.Half ? "half" : "__fp16"; + return llvm::StringRef(Policy.Half ? "half" : "__fp16"); case Float: return "float"; case Double: @@ -2591,7 +2591,7 @@ return "__float128"; case WChar_S: case WChar_U: - return Policy.MSWChar ? "__wchar_t" : "wchar_t"; + return llvm::StringRef(Policy.MSWChar ? "__wchar_t" : "wchar_t"); case Char16: return "char16_t"; case Char32: Index: clang/lib/ASTMatchers/Dynamic/Parser.cpp =================================================================== --- clang/lib/ASTMatchers/Dynamic/Parser.cpp +++ clang/lib/ASTMatchers/Dynamic/Parser.cpp @@ -398,7 +398,7 @@ // TODO: We could use different error codes for each/some to be more // explicit about the syntax error. if (BindToken.Kind != TokenInfo::TK_Ident || - BindToken.Text != TokenInfo::ID_Bind) { + BindToken.Text != llvm::StringRef(TokenInfo::ID_Bind)) { Error->addError(BindToken.Range, Error->ET_ParserMalformedBindExpr); return false; } Index: clang/lib/Basic/Diagnostic.cpp =================================================================== --- clang/lib/Basic/Diagnostic.cpp +++ clang/lib/Basic/Diagnostic.cpp @@ -29,15 +29,16 @@ StringRef string; switch (nullability.first) { case NullabilityKind::NonNull: - string = nullability.second ? "'nonnull'" : "'_Nonnull'"; + string = StringRef(nullability.second ? "'nonnull'" : "'_Nonnull'"); break; case NullabilityKind::Nullable: - string = nullability.second ? "'nullable'" : "'_Nullable'"; + string = StringRef(nullability.second ? "'nullable'" : "'_Nullable'"); break; case NullabilityKind::Unspecified: - string = nullability.second ? "'null_unspecified'" : "'_Null_unspecified'"; + string = StringRef(nullability.second ? "'null_unspecified'" + : "'_Null_unspecified'"); break; } Index: clang/lib/Basic/FileManager.cpp =================================================================== --- clang/lib/Basic/FileManager.cpp +++ clang/lib/Basic/FileManager.cpp @@ -280,7 +280,7 @@ else assert(NamedFileEnt.second == &UFE && "filename from getStatValue() refers to wrong file"); - InterndFileName = NamedFileEnt.first().data(); + InterndFileName = NamedFileEnt.first(); } if (UFE.isValid()) { // Already have an entry with this inode, return it. @@ -352,7 +352,7 @@ // Check to see if the file exists. If so, drop the virtual file FileData Data; - const char *InterndFileName = NamedFileEnt.first().data(); + StringRef InterndFileName = NamedFileEnt.first(); if (getStatValue(InterndFileName, Data, true, nullptr) == 0) { Data.Size = Size; Data.ModTime = ModificationTime; @@ -473,8 +473,8 @@ SmallString<128> FilePath(Path); FixupRelativePath(FilePath); - return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F, - StatCache.get(), *FS); + return FileSystemStatCache::get(FilePath, Data, isFile, F, StatCache.get(), + *FS); } bool FileManager::getNoncachedStatValue(StringRef Path, Index: clang/lib/Basic/FileSystemStatCache.cpp =================================================================== --- clang/lib/Basic/FileSystemStatCache.cpp +++ clang/lib/Basic/FileSystemStatCache.cpp @@ -120,7 +120,7 @@ // Cache file 'stat' results and directories with absolutely paths. if (!Data.IsDirectory || llvm::sys::path::is_absolute(Path)) - StatCalls[Path] = Data; + StatCalls[StringRef(Path)] = Data; return Result; } Index: clang/lib/Basic/IdentifierTable.cpp =================================================================== --- clang/lib/Basic/IdentifierTable.cpp +++ clang/lib/Basic/IdentifierTable.cpp @@ -654,13 +654,14 @@ bool isContextSensitive) { switch (kind) { case NullabilityKind::NonNull: - return isContextSensitive ? "nonnull" : "_Nonnull"; + return StringRef(isContextSensitive ? "nonnull" : "_Nonnull"); case NullabilityKind::Nullable: - return isContextSensitive ? "nullable" : "_Nullable"; + return StringRef(isContextSensitive ? "nullable" : "_Nullable"); case NullabilityKind::Unspecified: - return isContextSensitive ? "null_unspecified" : "_Null_unspecified"; + return StringRef(isContextSensitive ? "null_unspecified" + : "_Null_unspecified"); } llvm_unreachable("Unknown nullability kind."); } Index: clang/lib/Basic/TargetInfo.cpp =================================================================== --- clang/lib/Basic/TargetInfo.cpp +++ clang/lib/Basic/TargetInfo.cpp @@ -384,7 +384,9 @@ } // Check register names. - if (std::find(Names.begin(), Names.end(), Name) != Names.end()) + if (std::find_if(Names.begin(), Names.end(), [Name](const char *Other) { + return StringRef(Other) == Name; + }) != Names.end()) return true; // Check any additional names that we have. @@ -394,7 +396,7 @@ break; // Make sure the register that the additional name is for is within // the bounds of the register names from above. - if (AN == Name && ARN.RegNum < Names.size()) + if (StringRef(AN) == Name && ARN.RegNum < Names.size()) return true; } @@ -403,7 +405,7 @@ for (const char *A : GRA.Aliases) { if (!A) break; - if (A == Name) + if (StringRef(A) == Name) return true; } @@ -424,7 +426,7 @@ unsigned n; if (!Name.getAsInteger(0, n)) { assert(n < Names.size() && "Out of bounds register number!"); - return Names[n]; + return StringRef(Names[n]); } } @@ -435,7 +437,7 @@ break; // Make sure the register that the additional name is for is within // the bounds of the register names from above. - if (AN == Name && ARN.RegNum < Names.size()) + if (StringRef(AN) == Name && ARN.RegNum < Names.size()) return Name; } @@ -444,8 +446,8 @@ for (const char *A : RA.Aliases) { if (!A) break; - if (A == Name) - return RA.Register; + if (StringRef(A) == Name) + return StringRef(RA.Register); } return Name; Index: clang/lib/Basic/Targets.cpp =================================================================== --- clang/lib/Basic/Targets.cpp +++ clang/lib/Basic/Targets.cpp @@ -1989,14 +1989,14 @@ // If you edit the description strings, make sure you update // getPointerWidthV(). -static const char *const DataLayoutStringR600 = - "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" - "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"; +static const StringRef DataLayoutStringR600 = + "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" + "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"; -static const char *const DataLayoutStringSI = - "e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32" - "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" - "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"; +static const StringRef DataLayoutStringSI = + "e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32" + "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" + "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"; class AMDGPUTargetInfo final : public TargetInfo { static const Builtin::Info BuiltinInfo[]; @@ -4443,10 +4443,10 @@ RegParmMax = 6; // Pointers are 32-bit in x32. - resetDataLayout(IsX32 - ? "e-m:e-p:32:32-i64:64-f80:128-n8:16:32:64-S128" - : IsWinCOFF ? "e-m:w-i64:64-f80:128-n8:16:32:64-S128" - : "e-m:e-i64:64-f80:128-n8:16:32:64-S128"); + resetDataLayout( + IsX32 ? StringRef("e-m:e-p:32:32-i64:64-f80:128-n8:16:32:64-S128") + : IsWinCOFF ? "e-m:w-i64:64-f80:128-n8:16:32:64-S128" + : "e-m:e-i64:64-f80:128-n8:16:32:64-S128"); // Use fpret only for long double. RealTypeUsesObjCFPRet = (1 << TargetInfo::LongDouble); Index: clang/lib/Basic/Warnings.cpp =================================================================== --- clang/lib/Basic/Warnings.cpp +++ clang/lib/Basic/Warnings.cpp @@ -188,8 +188,8 @@ if (Report) { if (DiagIDs->getDiagnosticsInGroup(Flavor, Opt, _Diags)) - EmitUnknownDiagWarning(Diags, Flavor, isPositive ? "-W" : "-Wno-", - Opt); + EmitUnknownDiagWarning(Diags, Flavor, + StringRef(isPositive ? "-W" : "-Wno-"), Opt); } else { Diags.setSeverityForGroup(Flavor, Opt, Mapping); } @@ -218,8 +218,8 @@ if (Report) { if (DiagIDs->getDiagnosticsInGroup(Flavor, Opt, _Diags)) - EmitUnknownDiagWarning(Diags, Flavor, IsPositive ? "-R" : "-Rno-", - Opt); + EmitUnknownDiagWarning(Diags, Flavor, + StringRef(IsPositive ? "-R" : "-Rno-"), Opt); } else { Diags.setSeverityForGroup(Flavor, Opt, IsPositive ? diag::Severity::Remark Index: clang/lib/CodeGen/BackendUtil.cpp =================================================================== --- clang/lib/CodeGen/BackendUtil.cpp +++ clang/lib/CodeGen/BackendUtil.cpp @@ -868,7 +868,7 @@ llvm::GlobalVariable *GV = new llvm::GlobalVariable( *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, ModuleConstant); - GV->setSection(getSectionNameForBitcode(T)); + GV->setSection(llvm::StringRef(getSectionNameForBitcode(T))); UsedArray.push_back( ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); if (llvm::GlobalVariable *Old = @@ -891,7 +891,7 @@ GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true, llvm::GlobalValue::PrivateLinkage, CmdConstant); - GV->setSection(getSectionNameForCommandline(T)); + GV->setSection(llvm::StringRef(getSectionNameForCommandline(T))); UsedArray.push_back( ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType)); if (llvm::GlobalVariable *Old = Index: clang/lib/CodeGen/CGBlocks.cpp =================================================================== --- clang/lib/CodeGen/CGBlocks.cpp +++ clang/lib/CodeGen/CGBlocks.cpp @@ -1052,7 +1052,7 @@ llvm::Constant * CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr, const char *name) { - CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name); + CGBlockInfo blockInfo(blockExpr->getBlockDecl(), llvm::StringRef(name)); blockInfo.BlockExpression = blockExpr; // Compute information about the layout, etc., of this block. Index: clang/lib/CodeGen/CGBuiltin.cpp =================================================================== --- clang/lib/CodeGen/CGBuiltin.cpp +++ clang/lib/CodeGen/CGBuiltin.cpp @@ -1556,7 +1556,8 @@ const CGFunctionInfo &FuncInfo = CGM.getTypes().arrangeBuiltinFunctionCall(E->getType(), Args); llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo); - llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName); + llvm::Constant *Func = + CGM.CreateRuntimeFunction(FTy, llvm::StringRef(LibCallName)); return EmitCall(FuncInfo, Func, ReturnValueSlot(), Args); } @@ -2289,9 +2290,9 @@ llvm::FunctionType *FTy = llvm::FunctionType::get( Int32Ty, llvm::ArrayRef(ArgTys), false); Value *BCast = Builder.CreatePointerCast(Arg1, I8PTy); - return RValue::get( - Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name), - {Arg0, BCast, PacketSize, PacketAlign})); + return RValue::get(Builder.CreateCall( + CGM.CreateRuntimeFunction(FTy, llvm::StringRef(Name)), + {Arg0, BCast, PacketSize, PacketAlign})); } else { assert(4 == E->getNumArgs() && "Illegal number of parameters to pipe function"); @@ -2310,7 +2311,7 @@ if (Arg2->getType() != Int32Ty) Arg2 = Builder.CreateZExtOrTrunc(Arg2, Int32Ty); return RValue::get(Builder.CreateCall( - CGM.CreateRuntimeFunction(FTy, Name), + CGM.CreateRuntimeFunction(FTy, llvm::StringRef(Name)), {Arg0, Arg1, Arg2, BCast, PacketSize, PacketAlign})); } } @@ -2352,9 +2353,9 @@ // it to i32. if (Arg1->getType() != Int32Ty) Arg1 = Builder.CreateZExtOrTrunc(Arg1, Int32Ty); - return RValue::get( - Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name), - {Arg0, Arg1, PacketSize, PacketAlign})); + return RValue::get(Builder.CreateCall( + CGM.CreateRuntimeFunction(FTy, llvm::StringRef(Name)), + {Arg0, Arg1, PacketSize, PacketAlign})); } // OpenCL v2.0 s6.13.16, s9.17.3.5 - Built-in pipe commit read and write // functions @@ -2390,9 +2391,9 @@ llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), llvm::ArrayRef(ArgTys), false); - return RValue::get( - Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name), - {Arg0, Arg1, PacketSize, PacketAlign})); + return RValue::get(Builder.CreateCall( + CGM.CreateRuntimeFunction(FTy, llvm::StringRef(Name)), + {Arg0, Arg1, PacketSize, PacketAlign})); } // OpenCL v2.0 s6.13.16.4 Built-in pipe query functions case Builtin::BIget_pipe_num_packets: @@ -2412,8 +2413,9 @@ llvm::FunctionType *FTy = llvm::FunctionType::get( Int32Ty, llvm::ArrayRef(ArgTys), false); - return RValue::get(Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name), - {Arg0, PacketSize, PacketAlign})); + return RValue::get(Builder.CreateCall( + CGM.CreateRuntimeFunction(FTy, llvm::StringRef(Name)), + {Arg0, PacketSize, PacketAlign})); } // OpenCL v2.0 s6.13.9 - Address space qualifier functions. Index: clang/lib/CodeGen/CGClass.cpp =================================================================== --- clang/lib/CodeGen/CGClass.cpp +++ clang/lib/CodeGen/CGClass.cpp @@ -926,8 +926,8 @@ llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, Args, false); llvm::Constant *F = CGM.CreateRuntimeFunction( - FTy, Prologue ? "__asan_poison_intra_object_redzone" - : "__asan_unpoison_intra_object_redzone"); + FTy, llvm::StringRef(Prologue ? "__asan_poison_intra_object_redzone" + : "__asan_unpoison_intra_object_redzone")); llvm::Value *ThisPtr = LoadCXXThis(); ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy); Index: clang/lib/CodeGen/CGDebugInfo.cpp =================================================================== --- clang/lib/CodeGen/CGDebugInfo.cpp +++ clang/lib/CodeGen/CGDebugInfo.cpp @@ -136,7 +136,8 @@ auto *Scope = cast(LexicalBlockStack.back()); PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc); - if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename()) + if (PCLoc.isInvalid() || + Scope->getFilename() == llvm::StringRef(PCLoc.getFilename())) return; if (auto *LBF = dyn_cast(Scope)) { @@ -330,8 +331,9 @@ return cast(V); } - llvm::DIFile *F = DBuilder.createFile(remapDIPath(PLoc.getFilename()), - remapDIPath(getCurrentDirname())); + llvm::DIFile *F = + DBuilder.createFile(remapDIPath(llvm::StringRef(PLoc.getFilename())), + remapDIPath(getCurrentDirname())); DIFileCache[fname].reset(F); return F; Index: clang/lib/CodeGen/CGDeclCXX.cpp =================================================================== --- clang/lib/CodeGen/CGDeclCXX.cpp +++ clang/lib/CodeGen/CGDeclCXX.cpp @@ -267,7 +267,7 @@ if (!getLangOpts().AppleKext && !TLS) { // Set the section if needed. if (const char *Section = getTarget().getStaticInitSectionSpecifier()) - Fn->setSection(Section); + Fn->setSection(llvm::StringRef(Section)); } SetInternalFunctionAttributes(nullptr, Fn, FI); Index: clang/lib/CodeGen/CGException.cpp =================================================================== --- clang/lib/CodeGen/CGException.cpp +++ clang/lib/CodeGen/CGException.cpp @@ -222,8 +222,8 @@ static llvm::Constant *getPersonalityFn(CodeGenModule &CGM, const EHPersonality &Personality) { llvm::Constant *Fn = - CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true), - Personality.PersonalityFn); + CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true), + llvm::StringRef(Personality.PersonalityFn)); return Fn; } @@ -312,7 +312,8 @@ assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 && "Different EHPersonalities using the same personality function."); - llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn); + llvm::Function *Fn = + getModule().getFunction(llvm::StringRef(ObjCXX.PersonalityFn)); // Nothing to do if it's unused. if (!Fn || Fn->use_empty()) return; @@ -1369,8 +1370,9 @@ // anything on the EH stack which needs our help. const char *RethrowName = Personality.CatchallRethrowFn; if (RethrowName != nullptr && !isCleanup) { - EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName), - getExceptionFromSlot())->setDoesNotReturn(); + EmitRuntimeCall(getCatchallRethrowFn(CGM, llvm::StringRef(RethrowName)), + getExceptionFromSlot()) + ->setDoesNotReturn(); Builder.CreateUnreachable(); Builder.restoreIP(SavedIP); return EHResumeBlock; Index: clang/lib/CodeGen/CGExpr.cpp =================================================================== --- clang/lib/CodeGen/CGExpr.cpp +++ clang/lib/CodeGen/CGExpr.cpp @@ -2399,7 +2399,7 @@ PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc); if (PLoc.isValid()) { - StringRef FilenameString = PLoc.getFilename(); + StringRef FilenameString = llvm::StringRef(PLoc.getFilename()); int PathComponentsToStrip = CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip; Index: clang/lib/CodeGen/CGObjCGNU.cpp =================================================================== --- clang/lib/CodeGen/CGObjCGNU.cpp +++ clang/lib/CodeGen/CGObjCGNU.cpp @@ -79,8 +79,8 @@ if (!Function) { if (!FunctionName) return nullptr; - Function = - cast(CGM->CreateRuntimeFunction(FTy, FunctionName)); + Function = cast( + CGM->CreateRuntimeFunction(FTy, llvm::StringRef(FunctionName))); } return Function; } @@ -1219,7 +1219,7 @@ // It's quite ugly hard-coding this. Ideally we'd generate it using the host // platform's name mangling. const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE"; - auto *Vtable = TheModule.getGlobalVariable(vtableName); + auto *Vtable = TheModule.getGlobalVariable(llvm::StringRef(vtableName)); if (!Vtable) { Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true, llvm::GlobalValue::ExternalLinkage, @@ -2645,13 +2645,12 @@ // Emit alias registration calls: for (std::vector::iterator iter = ClassAliases.begin(); iter != ClassAliases.end(); ++iter) { - llvm::Constant *TheClass = - TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(), - true); - if (TheClass) { - TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy); - Builder.CreateCall(RegisterAlias, - {TheClass, MakeConstantString(iter->second)}); + llvm::Constant *TheClass = TheModule.getGlobalVariable( + llvm::StringRef(("_OBJC_CLASS_" + iter->first).c_str()), true); + if (TheClass) { + TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy); + Builder.CreateCall(RegisterAlias, + {TheClass, MakeConstantString(iter->second)}); } } // Jump to end: Index: clang/lib/CodeGen/CGObjCMac.cpp =================================================================== --- clang/lib/CodeGen/CGObjCMac.cpp +++ clang/lib/CodeGen/CGObjCMac.cpp @@ -297,8 +297,8 @@ name = "objc_setProperty_nonatomic_copy"; else name = "objc_setProperty_nonatomic"; - - return CGM.CreateRuntimeFunction(FTy, name); + + return CGM.CreateRuntimeFunction(FTy, llvm::StringRef(name)); } llvm::Constant *getCopyStructFn() { @@ -1428,12 +1428,12 @@ // Shamelessly stolen from Analysis/CFRefCount.cpp Selector GetNullarySelector(const char* name) const { - IdentifierInfo* II = &CGM.getContext().Idents.get(name); + IdentifierInfo *II = &CGM.getContext().Idents.get(llvm::StringRef(name)); return CGM.getContext().Selectors.getSelector(0, &II); } Selector GetUnarySelector(const char* name) const { - IdentifierInfo* II = &CGM.getContext().Idents.get(name); + IdentifierInfo *II = &CGM.getContext().Idents.get(llvm::StringRef(name)); return CGM.getContext().Selectors.getSelector(1, &II); } @@ -3015,12 +3015,12 @@ Values[2] = llvm::ConstantArray::get(AT, Properties); llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values); - llvm::GlobalVariable *GV = - CreateMetadataVar(Name, Init, - (ObjCABI == 2) ? "__DATA, __objc_const" : - "__OBJC,__property,regular,no_dead_strip", - CGM.getPointerAlign(), - true); + llvm::GlobalVariable *GV = CreateMetadataVar( + Name, Init, + llvm::StringRef((ObjCABI == 2) + ? "__DATA, __objc_const" + : "__OBJC,__property,regular,no_dead_strip"), + CGM.getPointerAlign(), true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy); } @@ -3353,11 +3353,12 @@ assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && "Forward metaclass reference has incorrect type."); GV->setInitializer(Init); - GV->setSection(Section); + GV->setSection(llvm::StringRef(Section)); GV->setAlignment(CGM.getPointerAlign().getQuantity()); CGM.addCompilerUsedGlobal(GV); } else - GV = CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true); + GV = CreateMetadataVar(Name, Init, llvm::StringRef(Section), + CGM.getPointerAlign(), true); DefinedClasses.push_back(GV); ImplementedClasses.push_back(Interface); // method definition entries must be clear for next implementation. @@ -3678,16 +3679,19 @@ StringRef Section; switch (Type) { case ObjCLabelType::ClassName: - Section = NonFragile ? "__TEXT,__objc_classname,cstring_literals" - : "__TEXT,__cstring,cstring_literals"; + Section = + llvm::StringRef(NonFragile ? "__TEXT,__objc_classname,cstring_literals" + : "__TEXT,__cstring,cstring_literals"); break; case ObjCLabelType::MethodVarName: - Section = NonFragile ? "__TEXT,__objc_methname,cstring_literals" - : "__TEXT,__cstring,cstring_literals"; + Section = + llvm::StringRef(NonFragile ? "__TEXT,__objc_methname,cstring_literals" + : "__TEXT,__cstring,cstring_literals"); break; case ObjCLabelType::MethodVarType: - Section = NonFragile ? "__TEXT,__objc_methtype,cstring_literals" - : "__TEXT,__cstring,cstring_literals"; + Section = + llvm::StringRef(NonFragile ? "__TEXT,__objc_methtype,cstring_literals" + : "__TEXT,__cstring,cstring_literals"); break; case ObjCLabelType::PropertyName: Section = "__TEXT,__cstring,cstring_literals"; @@ -5015,7 +5019,8 @@ buffer.push_back(0); auto *Entry = CGObjC.CreateCStringLiteral( - reinterpret_cast(buffer.data()), ObjCLabelType::ClassName); + llvm::StringRef(reinterpret_cast(buffer.data())), + ObjCLabelType::ClassName); return getConstantGEP(CGM.getLLVMContext(), Entry, 0, 0); } @@ -6229,8 +6234,8 @@ void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); const char *Prefix = "\01l_OBJC_$_CATEGORY_"; - - llvm::SmallString<64> ExtCatName(Prefix); + + llvm::SmallString<64> ExtCatName((llvm::StringRef(Prefix))); ExtCatName += Interface->getObjCRuntimeNameAsString(); ExtCatName += "_$_"; ExtCatName += OCD->getNameAsString(); @@ -6246,8 +6251,8 @@ Values[1] = ClassGV; std::vector Methods; - llvm::SmallString<64> MethodListName(Prefix); - + llvm::SmallString<64> MethodListName((llvm::StringRef(Prefix))); + MethodListName += "INSTANCE_METHODS_"; MethodListName += Interface->getObjCRuntimeNameAsString(); MethodListName += "_$_"; @@ -6261,7 +6266,7 @@ "__DATA, __objc_const", Methods); - MethodListName = Prefix; + MethodListName = llvm::StringRef(Prefix); MethodListName += "CLASS_METHODS_"; MethodListName += Interface->getObjCRuntimeNameAsString(); MethodListName += "_$_"; Index: clang/lib/CodeGen/CGOpenMPRuntime.cpp =================================================================== --- clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -1656,7 +1656,7 @@ }; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); - return CGM.CreateRuntimeFunction(FnTy, Name); + return CGM.CreateRuntimeFunction(FnTy, llvm::StringRef(Name)); } llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, @@ -1678,7 +1678,7 @@ }; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); - return CGM.CreateRuntimeFunction(FnTy, Name); + return CGM.CreateRuntimeFunction(FnTy, llvm::StringRef(Name)); } llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, @@ -1695,7 +1695,7 @@ }; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); - return CGM.CreateRuntimeFunction(FnTy, Name); + return CGM.CreateRuntimeFunction(FnTy, llvm::StringRef(Name)); } llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, @@ -1718,7 +1718,7 @@ }; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); - return CGM.CreateRuntimeFunction(FnTy, Name); + return CGM.CreateRuntimeFunction(FnTy, llvm::StringRef(Name)); } llvm::Constant * Index: clang/lib/CodeGen/CodeGenFunction.cpp =================================================================== --- clang/lib/CodeGen/CodeGenFunction.cpp +++ clang/lib/CodeGen/CodeGenFunction.cpp @@ -415,7 +415,8 @@ llvm::FunctionType *FunctionTy = llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false); - llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); + llvm::Constant *F = + CGM.CreateRuntimeFunction(FunctionTy, llvm::StringRef(Fn)); llvm::CallInst *CallSite = Builder.CreateCall( CGM.getIntrinsic(llvm::Intrinsic::returnaddress), llvm::ConstantInt::get(Int32Ty, 0), @@ -821,7 +822,8 @@ // The attribute "counting-function" is set to mcount function name which is // architecture dependent. if (CGM.getCodeGenOpts().InstrumentForProfiling) - Fn->addFnAttr("counting-function", getTarget().getMCountName()); + Fn->addFnAttr("counting-function", + llvm::StringRef(getTarget().getMCountName())); if (RetTy->isVoidType()) { // Void type; nothing to return. Index: clang/lib/CodeGen/CodeGenModule.cpp =================================================================== --- clang/lib/CodeGen/CodeGenModule.cpp +++ clang/lib/CodeGen/CodeGenModule.cpp @@ -1348,7 +1348,7 @@ SourceManager &SM = getContext().getSourceManager(); PresumedLoc PLoc = SM.getPresumedLoc(Loc); if (PLoc.isValid()) - return EmitAnnotationString(PLoc.getFilename()); + return EmitAnnotationString(llvm::StringRef(PLoc.getFilename())); return EmitAnnotationString(SM.getBufferName(Loc)); } @@ -3214,8 +3214,8 @@ // Without it LLVM can merge the string with a non unnamed_addr one during // LTO. Doing that changes the section it ends in, which surprises ld64. if (getTriple().isOSBinFormatMachO()) - GV->setSection(isUTF16 ? "__TEXT,__ustring" - : "__TEXT,__cstring,cstring_literals"); + GV->setSection(llvm::StringRef( + isUTF16 ? "__TEXT,__ustring" : "__TEXT,__cstring,cstring_literals")); // String. Fields[2] = @@ -3363,9 +3363,9 @@ const char *NSStringNonFragileABISection = "__DATA,__objc_stringobj,regular,no_dead_strip"; // FIXME. Fix section. - GV->setSection(LangOpts.ObjCRuntime.isNonFragile() - ? NSStringNonFragileABISection - : NSStringSection); + GV->setSection(llvm::StringRef(LangOpts.ObjCRuntime.isNonFragile() + ? NSStringNonFragileABISection + : NSStringSection)); Entry.second = GV; return ConstantAddress(GV, Alignment); @@ -3553,7 +3553,7 @@ GlobalName = ".str"; // Create a global variable for this. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, - GlobalName, Alignment); + llvm::StringRef(GlobalName), Alignment); if (Entry) *Entry = GV; return ConstantAddress(GV, Alignment); Index: clang/lib/CodeGen/ItaniumCXXABI.cpp =================================================================== --- clang/lib/CodeGen/ItaniumCXXABI.cpp +++ clang/lib/CodeGen/ItaniumCXXABI.cpp @@ -2124,7 +2124,8 @@ llvm::FunctionType::get(CGF.IntTy, paramTys, false); // Fetch the actual function. - llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name); + llvm::Constant *atexit = + CGF.CGM.CreateRuntimeFunction(atexitTy, llvm::StringRef(Name)); if (llvm::Function *fn = dyn_cast(atexit)) fn->setDoesNotThrow(); @@ -2840,8 +2841,8 @@ break; } - llvm::Constant *VTable = - CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy); + llvm::Constant *VTable = CGM.getModule().getOrInsertGlobal( + llvm::StringRef(VTableName), CGM.Int8PtrTy); llvm::Type *PtrDiffTy = CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); Index: clang/lib/CodeGen/MicrosoftCXXABI.cpp =================================================================== --- clang/lib/CodeGen/MicrosoftCXXABI.cpp +++ clang/lib/CodeGen/MicrosoftCXXABI.cpp @@ -2214,10 +2214,10 @@ if (CXXThreadLocalInits.empty()) return; - CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() == - llvm::Triple::x86 - ? "/include:___dyn_tls_init@12" - : "/include:__dyn_tls_init"); + CGM.AppendLinkerOptions( + llvm::StringRef(CGM.getTarget().getTriple().getArch() == llvm::Triple::x86 + ? "/include:___dyn_tls_init@12" + : "/include:__dyn_tls_init")); // This will create a GV in the .CRT$XDU section. It will point to our // initialization function. The CRT will call all of these function Index: clang/lib/CodeGen/TargetInfo.cpp =================================================================== --- clang/lib/CodeGen/TargetInfo.cpp +++ clang/lib/CodeGen/TargetInfo.cpp @@ -5135,7 +5135,7 @@ llvm::Function *Fn = cast(GV); - Fn->addFnAttr("interrupt", Kind); + Fn->addFnAttr("interrupt", llvm::StringRef(Kind)); ARMABIInfo::ABIKind ABI = cast(getABIInfo()).getABIKind(); if (ABI == ARMABIInfo::APCS) @@ -6272,8 +6272,7 @@ case MipsInterruptAttr::hw5: Kind = "hw5"; break; } - Fn->addFnAttr("interrupt", Kind); - + Fn->addFnAttr("interrupt", llvm::StringRef(Kind)); } bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, @@ -7457,7 +7456,7 @@ std::string Enc; public: FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} - StringRef str() {return Enc.c_str();} + StringRef str() { return llvm::StringRef(Enc.c_str()); } bool operator<(const FieldEncoding &rhs) const { if (HasName != rhs.HasName) return HasName; return Enc < rhs.Enc; @@ -7623,7 +7622,7 @@ E.State = IncompleteUsed; ++IncompleteUsedCount; } - return E.Str.c_str(); + return llvm::StringRef(E.Str.c_str()); } /// The XCore ABI includes a type information section that communicates symbol @@ -7848,7 +7847,7 @@ Lookup += 1<<1; if (QT.isVolatileQualified()) Lookup += 1<<2; - Enc += Table[Lookup]; + Enc += llvm::StringRef(Table[Lookup]); } /// Appends built-in types to Enc. @@ -7906,7 +7905,7 @@ default: return false; } - Enc += EncType; + Enc += llvm::StringRef(EncType); return true; } Index: clang/lib/Driver/Compilation.cpp =================================================================== --- clang/lib/Driver/Compilation.cpp +++ clang/lib/Driver/Compilation.cpp @@ -127,9 +127,9 @@ // output stream. if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) { std::error_code EC; - OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename, EC, - llvm::sys::fs::F_Append | - llvm::sys::fs::F_Text); + OS = new llvm::raw_fd_ostream( + llvm::StringRef(getDriver().CCPrintOptionsFilename), EC, + llvm::sys::fs::F_Append | llvm::sys::fs::F_Text); if (EC) { getDriver().Diag(clang::diag::err_drv_cc_print_options_failure) << EC.message(); Index: clang/lib/Driver/Driver.cpp =================================================================== --- clang/lib/Driver/Driver.cpp +++ clang/lib/Driver/Driver.cpp @@ -870,7 +870,8 @@ if (!ShowHidden) ExcludedFlagsBitmask |= HelpHidden; - getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), + getOpts().PrintHelp(llvm::outs(), llvm::StringRef(Name.c_str()), + llvm::StringRef(DriverTitle.c_str()), IncludedFlagsBitmask, ExcludedFlagsBitmask); } @@ -2312,7 +2313,7 @@ if (FinalOutput) LinkingOutput = FinalOutput->getValue(); else - LinkingOutput = getDefaultImageName(); + LinkingOutput = llvm::StringRef(getDefaultImageName()); } BuildJobsForAction(C, A, &C.getDefaultToolChain(), @@ -2567,13 +2568,13 @@ // If there is a single device option, just generate the job for it. if (OA->hasSingleDeviceDependence()) { InputInfo DevA; - OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC, - const char *DepBoundArch) { - DevA = - BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel, - /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, - CachedResults, /*BuildForOffloadDevice=*/true); - }); + OA->doOnEachDeviceDependence( + [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { + DevA = BuildJobsForAction( + C, DepA, DepTC, llvm::StringRef(DepBoundArch), AtTopLevel, + /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults, + /*BuildForOffloadDevice=*/true); + }); return DevA; } @@ -2585,7 +2586,8 @@ /*IsHostDependence=*/BuildForOffloadDevice, [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { OffloadDependencesInputInfo.push_back(BuildJobsForAction( - C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false, + C, DepA, DepTC, llvm::StringRef(DepBoundArch), + /*AtTopLevel=*/false, /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults, /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() != Action::OFK_None)); @@ -2643,7 +2645,8 @@ /*IsHostDependence=*/BuildForOffloadDevice, [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { OffloadDependencesInputInfo.push_back(BuildJobsForAction( - C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false, + C, DepA, DepTC, llvm::StringRef(DepBoundArch), + /* AtTopLevel */ false, /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults, /*BuildForOffloadDevice=*/DepA->getOffloadingDeviceKind() != Action::OFK_None)); @@ -2798,7 +2801,8 @@ StringRef Name = llvm::sys::path::filename(BaseInput); std::pair Split = Name.split('.'); std::string TmpName = GetTemporaryPath( - Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); + Split.first, + llvm::StringRef(types::getTypeTempSuffix(JA.getType(), IsCLMode()))); return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); } @@ -2839,13 +2843,13 @@ NamedOutput = MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image); } else if (MultipleArchs && !BoundArch.empty()) { - SmallString<128> Output(getDefaultImageName()); - Output += JA.getOffloadingFileNamePrefix(NormalizedTriple); - Output += "-"; - Output.append(BoundArch); + SmallString<128> Output((llvm::StringRef(getDefaultImageName()))); + Output += StringRef(JA.getOffloadingFileNamePrefix(NormalizedTriple)); + Output += StringRef("-"); + Output.append(StringRef(BoundArch)); NamedOutput = C.getArgs().MakeArgString(Output.c_str()); } else { - NamedOutput = getDefaultImageName(); + NamedOutput = llvm::StringRef(getDefaultImageName()); } } else if (JA.getType() == types::TY_PCH && IsCLMode()) { NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName).c_str()); @@ -2869,7 +2873,7 @@ JA.getType() == types::TY_LLVM_BC) Suffixed += ".tmp"; Suffixed += '.'; - Suffixed += Suffix; + Suffixed += llvm::StringRef(Suffix); NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); } @@ -2897,7 +2901,8 @@ StringRef Name = llvm::sys::path::filename(BaseInput); std::pair Split = Name.split('.'); std::string TmpName = GetTemporaryPath( - Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); + Split.first, + llvm::StringRef(types::getTypeTempSuffix(JA.getType(), IsCLMode()))); return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); } } Index: clang/lib/Driver/Job.cpp =================================================================== --- clang/lib/Driver/Job.cpp +++ clang/lib/Driver/Job.cpp @@ -145,7 +145,7 @@ Out.push_back(Arg); } else if (FirstInput) { FirstInput = false; - Out.push_back(Creator.getResponseFileFlag()); + Out.push_back(llvm::StringRef(Creator.getResponseFileFlag())); Out.push_back(ResponseFile); } } @@ -180,7 +180,7 @@ // Replace the input file name with the crashinfo's file name. OS << ' '; StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename); - printArg(OS, ShortName.str().c_str(), Quote); + printArg(OS, llvm::StringRef(ShortName.str().c_str()), Quote); continue; } } @@ -193,7 +193,7 @@ OS << ' '; printArg(OS, "-ivfsoverlay", Quote); OS << ' '; - printArg(OS, CrashInfo->VFSPath.str().c_str(), Quote); + printArg(OS, llvm::StringRef(CrashInfo->VFSPath.str().c_str()), Quote); // Insert -fmodules-cache-path and use the relative module directory // .cache/vfs/modules where we already dumped the modules. @@ -205,7 +205,7 @@ ModCachePath.append(RelModCacheDir.c_str()); OS << ' '; - printArg(OS, ModCachePath.c_str(), Quote); + printArg(OS, llvm::StringRef(ModCachePath.c_str()), Quote); } if (!ResponseFile.empty()) { @@ -331,7 +331,8 @@ const char *Executable_, const ArgStringList &Arguments_, ArrayRef Inputs) - : Command(Source_, Creator_, Executable_, Arguments_, Inputs) {} + : Command(Source_, Creator_, llvm::StringRef(Executable_), Arguments_, + Inputs) {} void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo) const { Index: clang/lib/Driver/MinGWToolChain.cpp =================================================================== --- clang/lib/Driver/MinGWToolChain.cpp +++ clang/lib/Driver/MinGWToolChain.cpp @@ -50,7 +50,7 @@ Arch = Archs[0].str(); // lib: Arch Linux, Ubuntu, Windows // lib64: openSUSE Linux - for (StringRef CandidateLib : {"lib", "lib64"}) { + for (StringRef CandidateLib : {StringRef("lib"), StringRef("lib64")}) { for (StringRef CandidateArch : Archs) { llvm::SmallString<1024> LibDir(Base); llvm::sys::path::append(LibDir, CandidateLib, "gcc", CandidateArch); Index: clang/lib/Driver/Multilib.cpp =================================================================== --- clang/lib/Driver/Multilib.cpp +++ clang/lib/Driver/Multilib.cpp @@ -214,7 +214,7 @@ } MultilibSet &MultilibSet::FilterOut(const char *Regex) { - llvm::Regex R(Regex); + llvm::Regex R((llvm::StringRef(Regex))); #ifndef NDEBUG std::string Error; if (!R.isValid(Error)) { Index: clang/lib/Driver/ToolChain.cpp =================================================================== --- clang/lib/Driver/ToolChain.cpp +++ clang/lib/Driver/ToolChain.cpp @@ -119,7 +119,7 @@ }; for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) - if (ProgName.endswith(DriverSuffixes[i].Suffix)) + if (ProgName.endswith(llvm::StringRef(DriverSuffixes[i].Suffix))) return &DriverSuffixes[i]; return nullptr; } @@ -277,9 +277,10 @@ return "i386"; if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb) - return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows) - ? "armhf" - : "arm"; + return llvm::StringRef( + (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows) + ? "armhf" + : "arm"); return TC.getArchName(); } @@ -333,7 +334,7 @@ } std::string ToolChain::GetFilePath(const char *Name) const { - return D.GetFilePath(Name, *this); + return D.GetFilePath(llvm::StringRef(Name), *this); } std::string ToolChain::GetProgramPath(StringRef Name) const { @@ -358,7 +359,8 @@ llvm::SmallString<8> LinkerName("ld."); LinkerName.append(UseLinker); - std::string LinkerPath(GetProgramPath(LinkerName.c_str())); + std::string LinkerPath( + GetProgramPath(llvm::StringRef(LinkerName.c_str()))); if (llvm::sys::fs::exists(LinkerPath)) return LinkerPath; } @@ -367,7 +369,7 @@ return ""; } - return GetProgramPath(DefaultLinker); + return GetProgramPath(llvm::StringRef(DefaultLinker)); } types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const { Index: clang/lib/Driver/ToolChains.cpp =================================================================== --- clang/lib/Driver/ToolChains.cpp +++ clang/lib/Driver/ToolChains.cpp @@ -162,11 +162,11 @@ case llvm::Triple::arm: if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) if (const char *Arch = ArmMachOArchName(A->getValue())) - return Arch; + return llvm::StringRef(Arch); if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) if (const char *Arch = ArmMachOArchNameCPU(A->getValue())) - return Arch; + return llvm::StringRef(Arch); return "arm"; } @@ -433,7 +433,7 @@ if (Sanitize.needsTsanRt()) AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan"); if (Sanitize.needsStatsRt()) { - StringRef OS = isTargetMacOS() ? "osx" : "iossim"; + StringRef OS = llvm::StringRef(isTargetMacOS() ? "osx" : "iossim"); AddLinkRuntimeLib(Args, CmdArgs, (Twine("libclang_rt.stats_client_") + OS + ".a").str(), /*AlwaysLink=*/true); @@ -511,8 +511,9 @@ // exists, and it is not the root path. if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) && StringRef(env) != "/") { - Args.append(Args.MakeSeparateArg( - nullptr, Opts.getOption(options::OPT_isysroot), env)); + Args.append(Args.MakeSeparateArg(nullptr, + Opts.getOption(options::OPT_isysroot), + llvm::StringRef(env))); } } } @@ -1025,7 +1026,8 @@ (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard) ? "hard" : "soft"; - CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a"; + CompilerRT += + llvm::StringRef(Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a"); AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true); } @@ -2517,7 +2519,9 @@ // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a. FilterNonExistent NonExistent( - Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS()); + Path, + llvm::StringRef(TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o"), + D.getVFS()); // Determine default multilib from: 32, 64, x32 // Also handle cases such as 64 on 32, 32 on 64, etc. @@ -3547,11 +3551,11 @@ switch (Type) { case ToolChain::CST_Libcxx: - CmdArgs.push_back(Profiling ? "-lc++_p" : "-lc++"); + CmdArgs.push_back(llvm::StringRef(Profiling ? "-lc++_p" : "-lc++")); break; case ToolChain::CST_Libstdcxx: - CmdArgs.push_back(Profiling ? "-lstdc++_p" : "-lstdc++"); + CmdArgs.push_back(llvm::StringRef(Profiling ? "-lstdc++_p" : "-lstdc++")); break; } } @@ -4048,7 +4052,7 @@ // code for N32 ABI only. if (tools::mips::hasMipsAbiArg(Args, "n32")) return "lib32"; - return Triple.isArch32Bit() ? "lib" : "lib64"; + return llvm::StringRef(Triple.isArch32Bit() ? "lib" : "lib64"); } // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and @@ -4068,7 +4072,7 @@ Triple.getEnvironment() == llvm::Triple::GNUX32) return "libx32"; - return Triple.isArch32Bit() ? "lib" : "lib64"; + return llvm::StringRef(Triple.isArch32Bit() ? "lib" : "lib64"); } static void addMultilibsFilePaths(const Driver &D, const MultilibSet &Multilibs, @@ -5245,7 +5249,7 @@ if (const char *EnvValue = getenv("SCE_ORBIS_SDK_DIR")) { if (!llvm::sys::fs::exists(EnvValue)) getDriver().Diag(clang::diag::warn_drv_ps4_sdk_dir) << EnvValue; - PS4SDKDir = EnvValue; + PS4SDKDir = llvm::StringRef(EnvValue); } else { PS4SDKDir = getDriver().Dir; llvm::sys::path::append(PS4SDKDir, "/../../"); Index: clang/lib/Driver/Tools.cpp =================================================================== --- clang/lib/Driver/Tools.cpp +++ clang/lib/Driver/Tools.cpp @@ -197,7 +197,7 @@ if (CombinedArg) { CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); } else { - CmdArgs.push_back(ArgName); + CmdArgs.push_back(llvm::StringRef(ArgName)); CmdArgs.push_back("."); } } else { @@ -205,7 +205,7 @@ CmdArgs.push_back( Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim))); } else { - CmdArgs.push_back(ArgName); + CmdArgs.push_back(llvm::StringRef(ArgName)); CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim))); } } @@ -216,14 +216,14 @@ if (CombinedArg) { CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); } else { - CmdArgs.push_back(ArgName); + CmdArgs.push_back(llvm::StringRef(ArgName)); CmdArgs.push_back("."); } } else { // Add the last path. if (CombinedArg) { CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs)); } else { - CmdArgs.push_back(ArgName); + CmdArgs.push_back(llvm::StringRef(ArgName)); CmdArgs.push_back(Args.MakeArgString(Dirs)); } } @@ -1256,11 +1256,11 @@ llvm_unreachable("Unexpected triple arch name"); case llvm::Triple::mips: case llvm::Triple::mipsel: - CPUName = DefMips32CPU; + CPUName = llvm::StringRef(DefMips32CPU); break; case llvm::Triple::mips64: case llvm::Triple::mips64el: - CPUName = DefMips64CPU; + CPUName = llvm::StringRef(DefMips64CPU); break; } } @@ -1268,25 +1268,25 @@ if (ABIName.empty() && (Triple.getVendor() == llvm::Triple::MipsTechnologies || Triple.getVendor() == llvm::Triple::ImaginationTechnologies)) { - ABIName = llvm::StringSwitch(CPUName) - .Case("mips1", "o32") - .Case("mips2", "o32") - .Case("mips3", "n64") - .Case("mips4", "n64") - .Case("mips5", "n64") - .Case("mips32", "o32") - .Case("mips32r2", "o32") - .Case("mips32r3", "o32") - .Case("mips32r5", "o32") - .Case("mips32r6", "o32") - .Case("mips64", "n64") - .Case("mips64r2", "n64") - .Case("mips64r3", "n64") - .Case("mips64r5", "n64") - .Case("mips64r6", "n64") - .Case("octeon", "n64") - .Case("p5600", "o32") - .Default(""); + ABIName = llvm::StringRef(llvm::StringSwitch(CPUName) + .Case("mips1", "o32") + .Case("mips2", "o32") + .Case("mips3", "n64") + .Case("mips4", "n64") + .Case("mips5", "n64") + .Case("mips32", "o32") + .Case("mips32r2", "o32") + .Case("mips32r3", "o32") + .Case("mips32r5", "o32") + .Case("mips32r6", "o32") + .Case("mips64", "n64") + .Case("mips64r2", "n64") + .Case("mips64r3", "n64") + .Case("mips64r5", "n64") + .Case("mips64r6", "n64") + .Case("octeon", "n64") + .Case("p5600", "o32") + .Default("")); } if (ABIName.empty()) { @@ -1300,10 +1300,10 @@ if (CPUName.empty()) { // Deduce CPU name from ABI name. - CPUName = llvm::StringSwitch(ABIName) - .Case("o32", DefMips32CPU) - .Cases("n32", "n64", DefMips64CPU) - .Default(""); + CPUName = llvm::StringRef(llvm::StringSwitch(ABIName) + .Case("o32", DefMips32CPU) + .Cases("n32", "n64", DefMips64CPU) + .Default("")); } // FIXME: Warn on inconsistent use of -march and -mabi. @@ -1460,7 +1460,7 @@ mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); CmdArgs.push_back("-target-abi"); - CmdArgs.push_back(ABIName.data()); + CmdArgs.push_back(llvm::StringRef(ABIName.data())); mips::FloatABI ABI = getMipsFloatABI(D, Args); if (ABI == mips::FloatABI::Soft) { @@ -1843,7 +1843,7 @@ .Default(nullptr); } if (CPU) - return CPU; + return llvm::StringRef(CPU); } // Select the default CPU if none was given (or detection failed). @@ -1867,7 +1867,7 @@ // On Android use targets compatible with gcc if (Triple.isAndroid()) - return Is64Bit ? "x86-64" : "i686"; + return llvm::StringRef(Is64Bit ? "x86-64" : "i686"); // Everything else goes to x86-64 in 64-bit mode. if (Is64Bit) @@ -2142,14 +2142,14 @@ // and pass through. llvm::StringMap OptionStrings; - OptionStrings.insert(std::make_pair("divd", false)); - OptionStrings.insert(std::make_pair("divf", false)); - OptionStrings.insert(std::make_pair("vec-divd", false)); - OptionStrings.insert(std::make_pair("vec-divf", false)); - OptionStrings.insert(std::make_pair("sqrtd", false)); - OptionStrings.insert(std::make_pair("sqrtf", false)); - OptionStrings.insert(std::make_pair("vec-sqrtd", false)); - OptionStrings.insert(std::make_pair("vec-sqrtf", false)); + OptionStrings.insert(std::make_pair(StringRef("divd"), false)); + OptionStrings.insert(std::make_pair(StringRef("divf"), false)); + OptionStrings.insert(std::make_pair(StringRef("vec-divd"), false)); + OptionStrings.insert(std::make_pair(StringRef("vec-divf"), false)); + OptionStrings.insert(std::make_pair(StringRef("sqrtd"), false)); + OptionStrings.insert(std::make_pair(StringRef("sqrtf"), false)); + OptionStrings.insert(std::make_pair(StringRef("vec-sqrtd"), false)); + OptionStrings.insert(std::make_pair(StringRef("vec-sqrtf"), false)); for (unsigned i = 0; i != NumOptions; ++i) { StringRef Val = A->getValue(i); @@ -2622,7 +2622,7 @@ continue; CmdArgs.push_back("-target-feature"); - CmdArgs.push_back(Name.data()); + CmdArgs.push_back(llvm::StringRef(Name.data())); } } @@ -2888,7 +2888,7 @@ for (StringRef Value : A->getValues()) { if (TakeNextArg) { - CmdArgs.push_back(Value.data()); + CmdArgs.push_back(llvm::StringRef(Value.data())); TakeNextArg = false; continue; } @@ -2921,7 +2921,8 @@ continue; } - MipsTargetFeature = llvm::StringSwitch(Value) + MipsTargetFeature = + llvm::StringRef(llvm::StringSwitch(Value) .Case("-mips1", "+mips1") .Case("-mips2", "+mips2") .Case("-mips3", "+mips3") @@ -2937,7 +2938,7 @@ .Case("-mips64r3", "+mips64r3") .Case("-mips64r5", "+mips64r5") .Case("-mips64r6", "+mips64r6") - .Default(nullptr); + .Default(nullptr)); if (!MipsTargetFeature.empty()) continue; } @@ -2963,7 +2964,7 @@ Value == "--mrelax-relocations=no") { UseRelaxRelocations = false; } else if (Value.startswith("-I")) { - CmdArgs.push_back(Value.data()); + CmdArgs.push_back(llvm::StringRef(Value.data())); // We need to consume the next argument if the current arg is a plain // -I. The next arg will be the include directory. if (Value == "-I") @@ -2972,7 +2973,7 @@ // "-gdwarf-N" options are not cc1as options. unsigned DwarfVersion = DwarfVersionNum(Value); if (DwarfVersion == 0) { // Send it onward, and let cc1as complain. - CmdArgs.push_back(Value.data()); + CmdArgs.push_back(llvm::StringRef(Value.data())); } else { RenderDebugEnablingArgs(Args, CmdArgs, codegenoptions::LimitedDebugInfo, @@ -3441,9 +3442,9 @@ CmdArgs.push_back("-x"); if (Args.hasArg(options::OPT_rewrite_objc)) - CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX)); + CmdArgs.push_back(llvm::StringRef(types::getTypeName(types::TY_PP_ObjCXX))); else - CmdArgs.push_back(types::getTypeName(Input.getType())); + CmdArgs.push_back(llvm::StringRef(types::getTypeName(Input.getType()))); } static VersionTuple getMSCompatibilityVersion(unsigned Version) { @@ -4196,7 +4197,7 @@ if (RMName) { CmdArgs.push_back("-mrelocation-model"); - CmdArgs.push_back(RMName); + CmdArgs.push_back(llvm::StringRef(RMName)); } if (PICLevel > 0) { CmdArgs.push_back("-pic-level"); @@ -4648,16 +4649,16 @@ Args.AddLastArg(CmdArgs, options::OPT_H); if (D.CCPrintHeaders && !D.CCGenDiagnostics) { CmdArgs.push_back("-header-include-file"); - CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename - : "-"); + CmdArgs.push_back(llvm::StringRef( + D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename : "-")); } Args.AddLastArg(CmdArgs, options::OPT_P); Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout); if (D.CCLogDiagnostics && !D.CCGenDiagnostics) { CmdArgs.push_back("-diagnostic-log-file"); - CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename - : "-"); + CmdArgs.push_back(llvm::StringRef( + D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename : "-")); } bool splitDwarfInlining = @@ -4832,7 +4833,7 @@ // Pass the path to compiler resource files. CmdArgs.push_back("-resource-dir"); - CmdArgs.push_back(D.ResourceDir.c_str()); + CmdArgs.push_back(llvm::StringRef(D.ResourceDir.c_str())); Args.AddLastArg(CmdArgs, options::OPT_working_directory); @@ -5679,7 +5680,7 @@ LanguageStandard = "-std=c++11"; } - CmdArgs.push_back(LanguageStandard.data()); + CmdArgs.push_back(llvm::StringRef(LanguageStandard.data())); } // -fno-borland-extensions is default. @@ -6119,7 +6120,7 @@ llvm::sys::path::replace_extension(F, ""); F += JA.getOffloadingFileNamePrefix(Triple.normalize()); F += "-"; - F += JA.getOffloadingArch(); + F += llvm::StringRef(JA.getOffloadingArch()); } } @@ -6265,7 +6266,7 @@ Arg->render(Args, OriginalArgs); SmallString<256> Flags; - Flags += Exec; + Flags += llvm::StringRef(Exec); for (StringRef OriginalArg : OriginalArgs) { SmallString<128> EscapedArg; EscapeSpacesAndBackslashes(OriginalArg, EscapedArg); @@ -6314,7 +6315,7 @@ auto CLCommand = getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput); C.addCommand(llvm::make_unique( - JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand))); + JA, *this, StringRef(Exec), CmdArgs, Inputs, std::move(CLCommand))); } else if (Args.hasArg(options::OPT__SLASH_fallback) && isa(JA)) { // In /fallback builds, run the main compilation even if the pch generation @@ -6322,7 +6323,8 @@ C.addCommand(llvm::make_unique(JA, *this, Exec, CmdArgs, Inputs)); } else { - C.addCommand(llvm::make_unique(JA, *this, Exec, CmdArgs, Inputs)); + C.addCommand(llvm::make_unique(JA, *this, StringRef(Exec), CmdArgs, + Inputs)); } // Handle the debug info splitting at object creation time if we're @@ -6586,7 +6588,7 @@ if (Args.hasArg(options::OPT__SLASH_Zl)) { CmdArgs.push_back("-D_VC_NODEFAULTLIB"); } else { - CmdArgs.push_back(FlagForCRT.data()); + CmdArgs.push_back(llvm::StringRef(FlagForCRT.data())); // This provides POSIX compatibility (maps 'open' to '_open'), which most // users want. The /Za flag to cl.exe turns this off, but it's not @@ -6717,7 +6719,7 @@ mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); CmdArgs.push_back("-target-abi"); - CmdArgs.push_back(ABIName.data()); + CmdArgs.push_back(llvm::StringRef(ABIName.data())); } void ClangAs::AddX86TargetArgs(const ArgList &Args, @@ -6844,7 +6846,7 @@ const char *RMName = RelocationModelName(RelocationModel); if (RMName) { CmdArgs.push_back("-mrelocation-model"); - CmdArgs.push_back(RMName); + CmdArgs.push_back(llvm::StringRef(RMName)); } // Optionally embed the -cc1as level arguments into the debug info, for build @@ -6856,7 +6858,7 @@ SmallString<256> Flags; const char *Exec = getToolChain().getDriver().getClangProgramPath(); - Flags += Exec; + Flags += llvm::StringRef(Exec); for (StringRef OriginalArg : OriginalArgs) { SmallString<128> EscapedArg; EscapeSpacesAndBackslashes(OriginalArg, EscapedArg); @@ -6907,7 +6909,8 @@ CmdArgs.push_back(Input.getFilename()); const char *Exec = getToolChain().getDriver().getClangProgramPath(); - C.addCommand(llvm::make_unique(JA, *this, Exec, CmdArgs, Inputs)); + C.addCommand( + llvm::make_unique(JA, *this, StringRef(Exec), CmdArgs, Inputs)); // Handle the debug info splitting at object creation time if we're // creating an object. @@ -7011,7 +7014,7 @@ if (types::canTypeBeUserSpecified(II.getType())) { CmdArgs.push_back("-x"); - CmdArgs.push_back(types::getTypeName(II.getType())); + CmdArgs.push_back(llvm::StringRef(types::getTypeName(II.getType()))); } if (II.isFilename()) @@ -7039,7 +7042,8 @@ } else GCCName = "gcc"; - StringRef Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName)); + StringRef Exec = Args.MakeArgString( + getToolChain().GetProgramPath(llvm::StringRef(GCCName))); C.addCommand(llvm::make_unique(JA, *this, Exec, CmdArgs, Inputs)); } @@ -7151,7 +7155,8 @@ II.getInputArg().render(Args, CmdArgs); } - auto Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str())); + auto Exec = + Args.MakeArgString(HTC.GetProgramPath(llvm::StringRef(AsName.c_str()))); C.addCommand(llvm::make_unique(JA, *this, Exec, CmdArgs, Inputs)); } @@ -7199,7 +7204,7 @@ CmdArgs.push_back("-r"); for (const auto &Opt : HTC.ExtraOpts) - CmdArgs.push_back(Opt.c_str()); + CmdArgs.push_back(llvm::StringRef(Opt.c_str())); CmdArgs.push_back("-march=hexagon"); std::string CpuVer = @@ -7352,7 +7357,8 @@ const ArgList &Args, StringRef LinkingOutput) const { - std::string Linker = getToolChain().GetProgramPath(getShortName()); + std::string Linker = + getToolChain().GetProgramPath(llvm::StringRef(getShortName())); ArgStringList CmdArgs; AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs); CmdArgs.push_back("-shared"); @@ -7906,8 +7912,8 @@ // the linker to use, so that it's lifetime will extend past a possible // dsymutil step. if (Version[0] >= 116 && NeedsTempPath(Inputs)) { - StringRef TmpPath = C.getArgs().MakeArgString( - D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object))); + StringRef TmpPath = C.getArgs().MakeArgString(D.GetTemporaryPath( + "cc", llvm::StringRef(types::getTypeTempSuffix(types::TY_Object)))); C.addTempFile(TmpPath); CmdArgs.push_back("-object_path_lto"); CmdArgs.push_back(TmpPath); @@ -7918,7 +7924,8 @@ // and 'ld' will use its default mechanism to search for libLTO.dylib. if (Version[0] >= 133) { // Search for libLTO in /../lib/libLTO.dylib - StringRef P = llvm::sys::path::parent_path(D.getInstalledDir()); + StringRef P = + llvm::sys::path::parent_path(llvm::StringRef(D.getInstalledDir())); SmallString<128> LibLTOPath(P); llvm::sys::path::append(LibLTOPath, "lib"); llvm::sys::path::append(LibLTOPath, "libLTO.dylib"); @@ -8414,7 +8421,8 @@ case llvm::Triple::sparcel: { CmdArgs.push_back("-32"); std::string CPU = getCPUName(Args, getToolChain().getTriple()); - CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple())); + CmdArgs.push_back(llvm::StringRef( + getSparcAsmModeForCPU(CPU, getToolChain().getTriple()))); AddAssemblerKPIC(getToolChain(), Args, CmdArgs); break; } @@ -8422,7 +8430,8 @@ case llvm::Triple::sparcv9: { CmdArgs.push_back("-64"); std::string CPU = getCPUName(Args, getToolChain().getTriple()); - CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple())); + CmdArgs.push_back(llvm::StringRef( + getSparcAsmModeForCPU(CPU, getToolChain().getTriple()))); AddAssemblerKPIC(getToolChain(), Args, CmdArgs); break; } @@ -8434,7 +8443,8 @@ mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName); CmdArgs.push_back("-mabi"); - CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data()); + CmdArgs.push_back( + llvm::StringRef(getGnuCompatibleMipsABIName(ABIName).data())); if (getToolChain().getArch() == llvm::Triple::mips64) CmdArgs.push_back("-EB"); @@ -8740,10 +8750,11 @@ mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName); CmdArgs.push_back("-march"); - CmdArgs.push_back(CPUName.data()); + CmdArgs.push_back(llvm::StringRef(CPUName.data())); CmdArgs.push_back("-mabi"); - CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data()); + CmdArgs.push_back( + llvm::StringRef(getGnuCompatibleMipsABIName(ABIName).data())); if (getToolChain().getArch() == llvm::Triple::mips || getToolChain().getArch() == llvm::Triple::mips64) @@ -8787,7 +8798,8 @@ case llvm::Triple::sparcel: case llvm::Triple::sparcv9: { std::string CPU = getCPUName(Args, getToolChain().getTriple()); - CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple())); + CmdArgs.push_back(llvm::StringRef( + getSparcAsmModeForCPU(CPU, getToolChain().getTriple()))); AddAssemblerKPIC(getToolChain(), Args, CmdArgs); break; } @@ -9030,10 +9042,11 @@ mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName); CmdArgs.push_back("-march"); - CmdArgs.push_back(CPUName.data()); + CmdArgs.push_back(llvm::StringRef(CPUName.data())); CmdArgs.push_back("-mabi"); - CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data()); + CmdArgs.push_back( + llvm::StringRef(getGnuCompatibleMipsABIName(ABIName).data())); if (getToolChain().getArch() == llvm::Triple::mips || getToolChain().getArch() == llvm::Triple::mips64) @@ -9049,7 +9062,8 @@ case llvm::Triple::sparcel: { CmdArgs.push_back("-32"); std::string CPU = getCPUName(Args, getToolChain().getTriple()); - CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple())); + CmdArgs.push_back(llvm::StringRef( + getSparcAsmModeForCPU(CPU, getToolChain().getTriple()))); AddAssemblerKPIC(getToolChain(), Args, CmdArgs); break; } @@ -9057,7 +9071,8 @@ case llvm::Triple::sparcv9: { CmdArgs.push_back("-64"); std::string CPU = getCPUName(Args, getToolChain().getTriple()); - CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple())); + CmdArgs.push_back(llvm::StringRef( + getSparcAsmModeForCPU(CPU, getToolChain().getTriple()))); AddAssemblerKPIC(getToolChain(), Args, CmdArgs); break; } @@ -9338,14 +9353,16 @@ case llvm::Triple::sparcel: { CmdArgs.push_back("-32"); std::string CPU = getCPUName(Args, getToolChain().getTriple()); - CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple())); + CmdArgs.push_back(llvm::StringRef( + getSparcAsmModeForCPU(CPU, getToolChain().getTriple()))); AddAssemblerKPIC(getToolChain(), Args, CmdArgs); break; } case llvm::Triple::sparcv9: { CmdArgs.push_back("-64"); std::string CPU = getCPUName(Args, getToolChain().getTriple()); - CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple())); + CmdArgs.push_back(llvm::StringRef( + getSparcAsmModeForCPU(CPU, getToolChain().getTriple()))); AddAssemblerKPIC(getToolChain(), Args, CmdArgs); break; } @@ -9402,10 +9419,10 @@ ABIName = getGnuCompatibleMipsABIName(ABIName); CmdArgs.push_back("-march"); - CmdArgs.push_back(CPUName.data()); + CmdArgs.push_back(llvm::StringRef(CPUName.data())); CmdArgs.push_back("-mabi"); - CmdArgs.push_back(ABIName.data()); + CmdArgs.push_back(llvm::StringRef(ABIName.data())); // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE, // or -mshared (not implemented) is in effect. @@ -9414,7 +9431,8 @@ // LLVM doesn't support -mplt yet and acts as if it is always given. // However, -mplt has no effect with the N64 ABI. - CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic"); + CmdArgs.push_back( + llvm::StringRef(ABIName == "64" ? "-KPIC" : "-call_nonpic")); if (getToolChain().getArch() == llvm::Triple::mips || getToolChain().getArch() == llvm::Triple::mips64) @@ -9676,14 +9694,14 @@ arm::appendEBLinkFlags(Args, CmdArgs, Triple); for (const auto &Opt : ToolChain.ExtraOpts) - CmdArgs.push_back(Opt.c_str()); + CmdArgs.push_back(llvm::StringRef(Opt.c_str())); if (!Args.hasArg(options::OPT_static)) { CmdArgs.push_back("--eh-frame-hdr"); } CmdArgs.push_back("-m"); - CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args)); + CmdArgs.push_back(llvm::StringRef(getLDMOption(ToolChain.getTriple(), Args))); if (Args.hasArg(options::OPT_static)) { if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb || @@ -9877,7 +9895,8 @@ StringRef LinkingOutput) const { const toolchains::NaClToolChain &ToolChain = static_cast(getToolChain()); - InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(), + InputInfo NaClMacros(types::TY_PP_Asm, + llvm::StringRef(ToolChain.GetNaClArmMacrosPath()), "nacl-arm-macros.s"); InputInfoList NewInputs; NewInputs.push_back(NaClMacros); @@ -10469,7 +10488,8 @@ CmdArgs.push_back(Args.MakeArgString("-incremental:no")); if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) { for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"}) - CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib)); + CmdArgs.push_back( + TC.getCompilerRTArgString(Args, llvm::StringRef(Lib))); // Make sure the dynamic runtime thunk is not optimized out at link time // to ensure proper SEH handling. CmdArgs.push_back(Args.MakeArgString( @@ -10480,7 +10500,8 @@ CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk")); } else { for (const auto &Lib : {"asan", "asan_cxx"}) - CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib)); + CmdArgs.push_back( + TC.getCompilerRTArgString(Args, llvm::StringRef(Lib))); } } @@ -10558,7 +10579,7 @@ } else { linkPath = Linker; llvm::sys::path::replace_extension(linkPath, "exe"); - linkPath = TC.GetProgramPath(linkPath.c_str()); + linkPath = TC.GetProgramPath(llvm::StringRef(linkPath.c_str())); } StringRef Exec = Args.MakeArgString(linkPath); @@ -10590,8 +10611,8 @@ // Optimization level. if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin)) - CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi" - : "/Oi-"); + CmdArgs.push_back(llvm::StringRef( + A->getOption().getID() == options::OPT_fbuiltin ? "/Oi" : "/Oi-")); if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) { if (A->getOption().getID() == options::OPT_O0) { CmdArgs.push_back("/Od"); @@ -10609,9 +10630,9 @@ } if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer, options::OPT_fno_omit_frame_pointer)) - CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer - ? "/Oy" - : "/Oy-"); + CmdArgs.push_back(llvm::StringRef( + A->getOption().getID() == options::OPT_fomit_frame_pointer ? "/Oy" + : "/Oy-")); if (!Args.hasArg(options::OPT_fwritable_strings)) CmdArgs.push_back("/GF"); @@ -10628,13 +10649,14 @@ if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections, options::OPT_fno_function_sections)) - CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections - ? "/Gy" - : "/Gy-"); + CmdArgs.push_back(llvm::StringRef( + A->getOption().getID() == options::OPT_ffunction_sections ? "/Gy" + : "/Gy-")); if (Arg *A = Args.getLastArg(options::OPT_fdata_sections, options::OPT_fno_data_sections)) - CmdArgs.push_back( - A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-"); + CmdArgs.push_back(llvm::StringRef( + A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" + : "/Gw-")); if (Args.hasArg(options::OPT_fsyntax_only)) CmdArgs.push_back("/Zs"); if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only, @@ -11082,8 +11104,8 @@ } else { EntryPoint.append("mainCRTStartup"); - CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic" - : "-Bdynamic"); + CmdArgs.push_back(llvm::StringRef( + Args.hasArg(options::OPT_static) ? "-Bstatic" : "-Bdynamic")); if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) { CmdArgs.push_back("--entry"); @@ -11145,7 +11167,8 @@ CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk")); } else { for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"}) - CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib)); + CmdArgs.push_back( + TC.getCompilerRTArgString(Args, llvm::StringRef(Lib))); // Make sure the dynamic runtime thunk is not optimized out at link time // to ensure proper SEH handling. CmdArgs.push_back(Args.MakeArgString("--undefined")); @@ -11639,7 +11662,7 @@ assert(TC.getTriple().isNVPTX() && "Wrong platform"); // Obtain architecture from the action. - CudaArch gpu_arch = StringToCudaArch(JA.getOffloadingArch()); + CudaArch gpu_arch = StringToCudaArch(llvm::StringRef(JA.getOffloadingArch())); assert(gpu_arch != CudaArch::UNKNOWN && "Device action expected to have an architecture."); @@ -11673,13 +11696,13 @@ OOpt = "0"; else if (A->getOption().matches(options::OPT_O)) { // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options. - OOpt = llvm::StringSwitch(A->getValue()) - .Case("1", "1") - .Case("2", "2") - .Case("3", "3") - .Case("s", "2") - .Case("z", "2") - .Default("2"); + OOpt = llvm::StringRef(llvm::StringSwitch(A->getValue()) + .Case("1", "1") + .Case("2", "2") + .Case("3", "3") + .Case("s", "2") + .Case("z", "2") + .Default("2")); } CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt)); } else { @@ -11727,7 +11750,7 @@ const char *gpu_arch_str = A->getOffloadingArch(); assert(gpu_arch_str && "Device action expected to have associated a GPU architecture!"); - CudaArch gpu_arch = StringToCudaArch(gpu_arch_str); + CudaArch gpu_arch = StringToCudaArch(llvm::StringRef(gpu_arch_str)); // We need to pass an Arch of the form "sm_XX" for cubin files and // "compute_XX" for ptx. Index: clang/lib/Driver/Types.cpp =================================================================== --- clang/lib/Driver/Types.cpp +++ clang/lib/Driver/Types.cpp @@ -233,7 +233,7 @@ types::ID types::lookupTypeForTypeSpecifier(llvm::StringRef Name) { for (unsigned i=0; i(MaxSplitBytes, FirstNonWhitespace)); + llvm::StringRef(Blanks), + std::max(MaxSplitBytes, FirstNonWhitespace)); } if (SpaceOffset != StringRef::npos && SpaceOffset != 0) { - StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks); - StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks); + StringRef BeforeCut = + Text.substr(0, SpaceOffset).rtrim(llvm::StringRef(Blanks)); + StringRef AfterCut = + Text.substr(SpaceOffset).ltrim(llvm::StringRef(Blanks)); return BreakableToken::Split(BeforeCut.size(), AfterCut.begin() - BeforeCut.end()); } @@ -183,7 +189,7 @@ } static StringRef getLineCommentIndentPrefix(StringRef Comment) { - static const char *const KnownPrefixes[] = {"///", "//", "//!"}; + static const StringRef KnownPrefixes[] = {"///", "//", "//!"}; StringRef LongestPrefix; for (StringRef KnownPrefix : KnownPrefixes) { if (Comment.startswith(KnownPrefix)) { @@ -335,14 +341,15 @@ --EndOfPreviousLine; // Calculate the end of the non-whitespace text in the previous line. - EndOfPreviousLine = - Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine); + EndOfPreviousLine = Lines[LineIndex - 1].find_last_not_of( + llvm::StringRef(Blanks), EndOfPreviousLine); if (EndOfPreviousLine == StringRef::npos) EndOfPreviousLine = 0; else ++EndOfPreviousLine; // Calculate the start of the non-whitespace text in the current line. - size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks); + size_t StartOfLine = + Lines[LineIndex].find_first_not_of(llvm::StringRef(Blanks)); if (StartOfLine == StringRef::npos) StartOfLine = Lines[LineIndex].rtrim("\r\n").size(); Index: clang/lib/Frontend/ASTUnit.cpp =================================================================== --- clang/lib/Frontend/ASTUnit.cpp +++ clang/lib/Frontend/ASTUnit.cpp @@ -1257,7 +1257,7 @@ Result.ModTime = 0; llvm::MD5 MD5Ctx; - MD5Ctx.update(Buffer->getBuffer().data()); + MD5Ctx.update(llvm::StringRef(Buffer->getBuffer().data())); MD5Ctx.final(Result.MD5); return Result; @@ -2257,7 +2257,7 @@ // Determine whether this global completion result is hidden by a local // completion result. If so, skip it. if (C->Kind != CXCursor_MacroDefinition && - HiddenNames.count(C->Completion->getTypedText())) + HiddenNames.count(llvm::StringRef(C->Completion->getTypedText()))) continue; // Adjust priority based on similar type classes. @@ -2265,9 +2265,9 @@ CodeCompletionString *Completion = C->Completion; if (!Context.getPreferredType().isNull()) { if (C->Kind == CXCursor_MacroDefinition) { - Priority = getMacroUsagePriority(C->Completion->getTypedText(), - S.getLangOpts(), - Context.getPreferredType()->isAnyPointerType()); + Priority = getMacroUsagePriority( + llvm::StringRef(C->Completion->getTypedText()), S.getLangOpts(), + Context.getPreferredType()->isAnyPointerType()); } else if (C->Type) { CanQualType Expected = S.Context.getCanonicalType( Index: clang/lib/Frontend/CompilerInstance.cpp =================================================================== --- clang/lib/Frontend/CompilerInstance.cpp +++ clang/lib/Frontend/CompilerInstance.cpp @@ -430,11 +430,12 @@ bool Preamble, bool UseGlobalModuleIndex) { HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); - IntrusiveRefCntPtr Reader(new ASTReader( - PP, Context, PCHContainerRdr, Extensions, - Sysroot.empty() ? "" : Sysroot.data(), DisablePCHValidation, - AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false, - HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex)); + IntrusiveRefCntPtr Reader( + new ASTReader(PP, Context, PCHContainerRdr, Extensions, + llvm::StringRef(Sysroot.empty() ? "" : Sysroot.data()), + DisablePCHValidation, AllowPCHWithCompilerErrors, + /*AllowConfigurationMismatch*/ false, + HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex)); // We need the external source to be set up before we read the AST, because // eagerly-deserialized declarations may use it. @@ -1316,12 +1317,12 @@ ModuleManager = new ASTReader( getPreprocessor(), getASTContext(), getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions, - Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation, + llvm::StringRef(Sysroot.empty() ? "" : Sysroot.c_str()), + PPOpts.DisablePCHValidation, /*AllowASTWithCompilerErrors=*/false, /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders, - getFrontendOpts().UseGlobalModuleIndex, - std::move(ReadTimer)); + getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer)); if (hasASTConsumer()) { ModuleManager->setDeserializationListener( getASTConsumer().GetASTDeserializationListener()); Index: clang/lib/Frontend/CompilerInvocation.cpp =================================================================== --- clang/lib/Frontend/CompilerInvocation.cpp +++ clang/lib/Frontend/CompilerInvocation.cpp @@ -1455,7 +1455,7 @@ Path = Buffer.str(); } - Opts.AddPath(Path.c_str(), Group, IsFramework, + Opts.AddPath(llvm::StringRef(Path.c_str()), Group, IsFramework, /*IgnoreSysroot*/ true); IsIndexHeaderMap = false; } Index: clang/lib/Frontend/DependencyFile.cpp =================================================================== --- clang/lib/Frontend/DependencyFile.cpp +++ clang/lib/Frontend/DependencyFile.cpp @@ -259,7 +259,7 @@ /// considered as a dependency. bool DFGImpl::FileMatchesDepCriteria(const char *Filename, SrcMgr::CharacteristicKind FileType) { - if (isSpecialFilename(Filename)) + if (isSpecialFilename(llvm::StringRef(Filename))) return false; if (IncludeSystemHeaders) Index: clang/lib/Frontend/FrontendActions.cpp =================================================================== --- clang/lib/Frontend/FrontendActions.cpp +++ clang/lib/Frontend/FrontendActions.cpp @@ -455,7 +455,7 @@ std::unique_ptr Reader(new ASTReader( CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions, - Sysroot.empty() ? "" : Sysroot.c_str(), + llvm::StringRef(Sysroot.empty() ? "" : Sysroot.c_str()), /*DisableValidation*/ false, /*AllowPCHWithCompilerErrors*/ false, /*AllowConfigurationMismatch*/ true, Index: clang/lib/Frontend/HeaderIncludeGen.cpp =================================================================== --- clang/lib/Frontend/HeaderIncludeGen.cpp +++ clang/lib/Frontend/HeaderIncludeGen.cpp @@ -159,8 +159,8 @@ // FIXME: Identify headers in a more robust way than comparing their name to // "" and "" in a bunch of places. if (ShowHeader && Reason == PPCallbacks::EnterFile && - UserLoc.getFilename() != StringRef("")) { - PrintHeaderInfo(OutputFile, UserLoc.getFilename(), ShowDepth, IncludeDepth, - MSStyle); + llvm::StringRef(UserLoc.getFilename()) != StringRef("")) { + PrintHeaderInfo(OutputFile, llvm::StringRef(UserLoc.getFilename()), + ShowDepth, IncludeDepth, MSStyle); } } Index: clang/lib/Frontend/InitPreprocessor.cpp =================================================================== --- clang/lib/Frontend/InitPreprocessor.cpp +++ clang/lib/Frontend/InitPreprocessor.cpp @@ -89,7 +89,7 @@ return; } - AddImplicitInclude(Builder, OriginalFile); + AddImplicitInclude(Builder, llvm::StringRef(OriginalFile)); } /// \brief Add an implicit \#include using the original file used to generate @@ -190,14 +190,15 @@ /// the width, suffix, and signedness of the given type static void DefineTypeSize(const Twine &MacroName, TargetInfo::IntType Ty, const TargetInfo &TI, MacroBuilder &Builder) { - DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty), + DefineTypeSize(MacroName, TI.getTypeWidth(Ty), + llvm::StringRef(TI.getTypeConstantSuffix(Ty)), TI.isTypeSigned(Ty), Builder); } static void DefineFmt(const Twine &Prefix, TargetInfo::IntType Ty, const TargetInfo &TI, MacroBuilder &Builder) { bool IsSigned = TI.isTypeSigned(Ty); - StringRef FmtModifier = TI.getTypeFormatModifier(Ty); + StringRef FmtModifier = llvm::StringRef(TI.getTypeFormatModifier(Ty)); for (const char *Fmt = IsSigned ? "di" : "ouxX"; *Fmt; ++Fmt) { Builder.defineMacro(Prefix + "_FMT" + Twine(*Fmt) + "__", Twine("\"") + FmtModifier + Twine(*Fmt) + "\""); Index: clang/lib/Frontend/PrintPreprocessedOutput.cpp =================================================================== --- clang/lib/Frontend/PrintPreprocessedOutput.cpp +++ clang/lib/Frontend/PrintPreprocessedOutput.cpp @@ -275,7 +275,7 @@ CurLine = NewLine; CurFilename.clear(); - CurFilename += UserLoc.getFilename(); + CurFilename += llvm::StringRef(UserLoc.getFilename()); FileType = NewFileType; if (DisableLineMarkers) { Index: clang/lib/Frontend/Rewrite/RewriteMacros.cpp =================================================================== --- clang/lib/Frontend/Rewrite/RewriteMacros.cpp +++ clang/lib/Frontend/Rewrite/RewriteMacros.cpp @@ -167,7 +167,7 @@ // Comment out a whole run of tokens instead of bracketing each one with // comments. Add a leading space if RawTok didn't have one. bool HasSpace = RawTok.hasLeadingSpace(); - RB.InsertTextAfter(RawOffs, &" /*"[HasSpace]); + RB.InsertTextAfter(RawOffs, llvm::StringRef(&" /*"[HasSpace])); unsigned EndPos; do { Index: clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp =================================================================== --- clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp +++ clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp @@ -863,9 +863,9 @@ CDecl = CatDecl->getClassInterface(); std::string RecName = CDecl->getName(); RecName += "_IMPL"; - RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, - SourceLocation(), SourceLocation(), - &Context->Idents.get(RecName.c_str())); + RecordDecl *RD = RecordDecl::Create( + *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), + &Context->Idents.get(llvm::StringRef(RecName.c_str()))); QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); unsigned UnsignedIntSize = static_cast(Context->getTypeSize(Context->UnsignedIntTy)); @@ -1623,7 +1623,7 @@ PresumedLoc PLoc = SM->getPresumedLoc(Loc); LineString += utostr(PLoc.getLine()); LineString += " \""; - LineString += Lexer::Stringify(PLoc.getFilename()); + LineString += Lexer::Stringify(llvm::StringRef(PLoc.getFilename())); LineString += "\"\n"; } } @@ -3064,7 +3064,7 @@ PresumedLoc PLoc = SM->getPresumedLoc(Location); LineString += utostr(PLoc.getLine()); LineString += " \""; - LineString += Lexer::Stringify(PLoc.getFilename()); + LineString += Lexer::Stringify(llvm::StringRef(PLoc.getFilename())); if (isa(D)) LineString += "\""; else LineString += "\"\n"; @@ -5166,8 +5166,8 @@ "RewriteByRefVar: can't find ';' or ','"); SourceLocation separatorLoc = startLoc.getLocWithOffset(separatorBuf-startInitializerBuf); - - InsertText(separatorLoc, lastDecl ? "}" : "};\n"); + + InsertText(separatorLoc, llvm::StringRef(lastDecl ? "}" : "};\n")); } } @@ -5301,11 +5301,10 @@ // Initialize the block descriptor. std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA"; - VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, - SourceLocation(), SourceLocation(), - &Context->Idents.get(DescData.c_str()), - Context->VoidPtrTy, nullptr, - SC_Static); + VarDecl *NewVD = + VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), + &Context->Idents.get(llvm::StringRef(DescData.c_str())), + Context->VoidPtrTy, nullptr, SC_Static); UnaryOperator *DescRefExpr = new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false, Context->VoidPtrTy, @@ -5361,8 +5360,8 @@ std::string Name(ND->getNameAsString()); std::string RecName; RewriteByRefString(RecName, Name, ND, true); - IdentifierInfo *II = &Context->Idents.get(RecName.c_str() - + sizeof("struct")); + IdentifierInfo *II = &Context->Idents.get( + llvm::StringRef(RecName.c_str() + sizeof("struct"))); RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), II); @@ -7522,9 +7521,9 @@ CDecl = CatDecl->getClassInterface(); std::string RecName = CDecl->getName(); RecName += "_IMPL"; - RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, - SourceLocation(), SourceLocation(), - &Context->Idents.get(RecName.c_str())); + RecordDecl *RD = RecordDecl::Create( + *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), + &Context->Idents.get(llvm::StringRef(RecName.c_str()))); QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); unsigned UnsignedIntSize = static_cast(Context->getTypeSize(Context->UnsignedIntTy)); Index: clang/lib/Frontend/Rewrite/RewriteObjC.cpp =================================================================== --- clang/lib/Frontend/Rewrite/RewriteObjC.cpp +++ clang/lib/Frontend/Rewrite/RewriteObjC.cpp @@ -4426,11 +4426,10 @@ // Initialize the block descriptor. std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA"; - VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, - SourceLocation(), SourceLocation(), - &Context->Idents.get(DescData.c_str()), - Context->VoidPtrTy, nullptr, - SC_Static); + VarDecl *NewVD = + VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), + &Context->Idents.get(llvm::StringRef(DescData.c_str())), + Context->VoidPtrTy, nullptr, SC_Static); UnaryOperator *DescRefExpr = new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false, Context->VoidPtrTy, @@ -4485,8 +4484,8 @@ std::string Name(ND->getNameAsString()); std::string RecName; RewriteByRefString(RecName, Name, ND, true); - IdentifierInfo *II = &Context->Idents.get(RecName.c_str() - + sizeof("struct")); + IdentifierInfo *II = &Context->Idents.get( + llvm::StringRef(RecName.c_str() + sizeof("struct"))); RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), II); @@ -5650,14 +5649,14 @@ InstanceMethods.push_back(Setter); } RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(), - true, "CATEGORY_", FullCategoryName.c_str(), - Result); - + true, "CATEGORY_", + llvm::StringRef(FullCategoryName.c_str()), Result); + // Build _objc_method_list for class's class methods if needed RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(), - false, "CATEGORY_", FullCategoryName.c_str(), - Result); - + false, "CATEGORY_", + llvm::StringRef(FullCategoryName.c_str()), Result); + // Protocols referenced in class declaration? // Null CDecl is case of a category implementation with no category interface if (CDecl) Index: clang/lib/Frontend/SerializedDiagnosticPrinter.cpp =================================================================== --- clang/lib/Frontend/SerializedDiagnosticPrinter.cpp +++ clang/lib/Frontend/SerializedDiagnosticPrinter.cpp @@ -104,7 +104,7 @@ : SerializedDiagnosticReader(), Writer(Writer) {} std::error_code mergeRecordsFromFile(const char *File) { - return readDiagnostics(File); + return readDiagnostics(llvm::StringRef(File)); } protected: @@ -805,8 +805,8 @@ } std::error_code EC; - auto OS = llvm::make_unique(State->OutputFile.c_str(), - EC, llvm::sys::fs::F_None); + auto OS = llvm::make_unique(State->OutputFile, EC, + llvm::sys::fs::F_None); if (EC) { getMetaDiags()->Report(diag::warn_fe_serialized_diag_failure) << State->OutputFile << EC.message(); Index: clang/lib/Frontend/TextDiagnostic.cpp =================================================================== --- clang/lib/Frontend/TextDiagnostic.cpp +++ clang/lib/Frontend/TextDiagnostic.cpp @@ -813,7 +813,7 @@ if (DiagOpts->ShowColors) OS.changeColor(savedColor, true); - emitFilename(PLoc.getFilename(), SM); + emitFilename(llvm::StringRef(PLoc.getFilename()), SM); switch (DiagOpts->getFormat()) { case DiagnosticOptions::Clang: OS << ':' << LineNo; break; case DiagnosticOptions::MSVC: OS << '(' << LineNo; break; @@ -1282,7 +1282,7 @@ break; OS << "fix-it:\""; - OS.write_escaped(PLoc.getFilename()); + OS.write_escaped(llvm::StringRef(PLoc.getFilename())); OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second) << ':' << SM.getColumnNumber(BInfo.first, BInfo.second) << '-' << SM.getLineNumber(EInfo.first, EInfo.second) Index: clang/lib/Lex/HeaderSearch.cpp =================================================================== --- clang/lib/Lex/HeaderSearch.cpp +++ clang/lib/Lex/HeaderSearch.cpp @@ -717,7 +717,7 @@ // Skip querying potentially lots of directories for this lookup. i = CacheLookup.HitIdx; if (CacheLookup.MappedName) - Filename = CacheLookup.MappedName; + Filename = llvm::StringRef(CacheLookup.MappedName); } else { // Otherwise, this is the first query, or the previous query didn't match // our search start. We will fill in our found location below, so prime the Index: clang/lib/Lex/Lexer.cpp =================================================================== --- clang/lib/Lex/Lexer.cpp +++ clang/lib/Lex/Lexer.cpp @@ -2623,13 +2623,13 @@ const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>"; size_t TermLen = CMK == CMK_Perforce ? 5 : 7; auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen); - size_t Pos = RestOfBuffer.find(Terminator); + size_t Pos = RestOfBuffer.find(llvm::StringRef(Terminator)); while (Pos != StringRef::npos) { // Must occur at start of line. if (Pos == 0 || (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) { RestOfBuffer = RestOfBuffer.substr(Pos+TermLen); - Pos = RestOfBuffer.find(Terminator); + Pos = RestOfBuffer.find(llvm::StringRef(Terminator)); continue; } return RestOfBuffer.data()+Pos; Index: clang/lib/Lex/PPDirectives.cpp =================================================================== --- clang/lib/Lex/PPDirectives.cpp +++ clang/lib/Lex/PPDirectives.cpp @@ -1800,7 +1800,8 @@ #endif } const FileEntry *File = LookupFile( - FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, + FilenameLoc, + LangOpts.MSVCCompat ? StringRef(NormalizedPath.c_str()) : Filename, isAngled, LookupFrom, LookupFromFile, CurDir, Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr, &SuggestedModule); @@ -1816,11 +1817,12 @@ HeaderInfo.AddSearchPath(DL, isAngled); // Try the lookup again, skipping the cache. - File = LookupFile( - FilenameLoc, - LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled, - LookupFrom, LookupFromFile, CurDir, nullptr, nullptr, - &SuggestedModule, /*SkipCache*/ true); + File = + LookupFile(FilenameLoc, + LangOpts.MSVCCompat ? StringRef(NormalizedPath.c_str()) + : Filename, + isAngled, LookupFrom, LookupFromFile, CurDir, nullptr, + nullptr, &SuggestedModule, /*SkipCache*/ true); } } } @@ -1832,11 +1834,10 @@ if (isAngled) { File = LookupFile( FilenameLoc, - LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false, - LookupFrom, LookupFromFile, CurDir, + LangOpts.MSVCCompat ? StringRef(NormalizedPath.c_str()) : Filename, + false, LookupFrom, LookupFromFile, CurDir, Callbacks ? &SearchPath : nullptr, - Callbacks ? &RelativePath : nullptr, - &SuggestedModule); + Callbacks ? &RelativePath : nullptr, &SuggestedModule); if (File) { SourceRange Range(FilenameTok.getLocation(), CharEnd); Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) << @@ -1944,8 +1945,8 @@ // Notify the callback object that we've seen an inclusion directive. Callbacks->InclusionDirective( HashLoc, IncludeTok, - LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled, - FilenameRange, File, SearchPath, RelativePath, + LangOpts.MSVCCompat ? StringRef(NormalizedPath.c_str()) : Filename, + isAngled, FilenameRange, File, SearchPath, RelativePath, ShouldEnter ? nullptr : SuggestedModule.getModule()); } Index: clang/lib/Lex/PPMacroExpansion.cpp =================================================================== --- clang/lib/Lex/PPMacroExpansion.cpp +++ clang/lib/Lex/PPMacroExpansion.cpp @@ -301,7 +301,7 @@ /// table and mark it as a builtin macro to be expanded. static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){ // Get the identifier. - IdentifierInfo *Id = PP.getIdentifierInfo(Name); + IdentifierInfo *Id = PP.getIdentifierInfo(llvm::StringRef(Name)); // Mark it as being a macro that is builtin. MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation()); @@ -1624,7 +1624,7 @@ // Escape this filename. Turn '\' -> '\\' '"' -> '\"' SmallString<128> FN; if (PLoc.isValid()) { - FN += PLoc.getFilename(); + FN += llvm::StringRef(PLoc.getFilename()); Lexer::Stringify(FN); OS << '"' << FN << '"'; } Index: clang/lib/Lex/PTHLexer.cpp =================================================================== --- clang/lib/Lex/PTHLexer.cpp +++ clang/lib/Lex/PTHLexer.cpp @@ -336,7 +336,7 @@ static internal_key_type ReadKey(const unsigned char* d, unsigned) { unsigned char k = *(d++); // Read the entry kind. - return std::make_pair(k, (const char*) d); + return std::make_pair(k, StringRef((const char *)d)); } }; Index: clang/lib/Lex/Pragma.cpp =================================================================== --- clang/lib/Lex/Pragma.cpp +++ clang/lib/Lex/Pragma.cpp @@ -451,8 +451,9 @@ PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation()); if (PLoc.isInvalid()) return; - - unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename()); + + unsigned FilenameID = + SourceMgr.getLineTableFilenameID(llvm::StringRef(PLoc.getFilename())); // Notify the client, if desired, that we are in a new source file. if (Callbacks) @@ -1011,12 +1012,12 @@ if (!PP.getDiagnostics().popMappings(DiagLoc)) PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop); else if (Callbacks) - Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace); + Callbacks->PragmaDiagnosticPop(DiagLoc, llvm::StringRef(Namespace)); return; } else if (II->isStr("push")) { PP.getDiagnostics().pushMappings(DiagLoc); if (Callbacks) - Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace); + Callbacks->PragmaDiagnosticPush(DiagLoc, llvm::StringRef(Namespace)); return; } @@ -1067,7 +1068,8 @@ PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning) << WarningName; else if (Callbacks) - Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName); + Callbacks->PragmaDiagnostic(DiagLoc, llvm::StringRef(Namespace), SV, + WarningName); } }; @@ -1237,7 +1239,8 @@ public: PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind, StringRef Namespace = StringRef()) - : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {} + : PragmaHandler(llvm::StringRef(PragmaKind(Kind, true))), Kind(Kind), + Namespace(Namespace) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) override { @@ -1471,7 +1474,8 @@ /// editor-only /// pragma, just skipped by compiler. struct PragmaRegionHandler : public PragmaHandler { - PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { } + PragmaRegionHandler(const char *pragma) + : PragmaHandler(llvm::StringRef(pragma)) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &NameTok) override { Index: clang/lib/Parse/ParseCXXInlineMethods.cpp =================================================================== --- clang/lib/Parse/ParseCXXInlineMethods.cpp +++ clang/lib/Parse/ParseCXXInlineMethods.cpp @@ -93,8 +93,9 @@ Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) << Delete; SkipUntil(tok::semi); - } else if (ExpectAndConsume(tok::semi, diag::err_expected_after, - Delete ? "delete" : "default")) { + } else if (ExpectAndConsume( + tok::semi, diag::err_expected_after, + llvm::StringRef(Delete ? "delete" : "default"))) { SkipUntil(tok::semi); } Index: clang/lib/Parse/ParseDecl.cpp =================================================================== --- clang/lib/Parse/ParseDecl.cpp +++ clang/lib/Parse/ParseDecl.cpp @@ -2356,8 +2356,9 @@ Sema::LookupOrdinaryName); Diag(Loc, diag::err_use_of_tag_name_without_tag) - << TokenName << TagName << getLangOpts().CPlusPlus - << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName); + << TokenName << TagName << getLangOpts().CPlusPlus + << FixItHint::CreateInsertion(Tok.getLocation(), + llvm::StringRef(FixitTagName)); if (Actions.LookupParsedName(R, getCurScope(), SS)) { for (LookupResult::iterator I = R.begin(), IEnd = R.end(); Index: clang/lib/Parse/ParseDeclCXX.cpp =================================================================== --- clang/lib/Parse/ParseDeclCXX.cpp +++ clang/lib/Parse/ParseDeclCXX.cpp @@ -683,10 +683,11 @@ // Eat ';'. DeclEnd = Tok.getLocation(); - if (ExpectAndConsume(tok::semi, diag::err_expected_after, - !Attrs.empty() ? "attributes list" - : IsAliasDecl ? "alias declaration" - : "using declaration")) + if (ExpectAndConsume( + tok::semi, diag::err_expected_after, + llvm::StringRef(!Attrs.empty() ? "attributes list" + : IsAliasDecl ? "alias declaration" + : "using declaration"))) SkipUntil(tok::semi); // Diagnose an attempt to declare a templated using-declaration. @@ -1585,8 +1586,9 @@ if (Tok.isNot(tok::semi)) { const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy(); // A semicolon was missing after this declaration. Diagnose and recover. - ExpectAndConsume(tok::semi, diag::err_expected_after, - DeclSpec::getSpecifierName(TagType, PPol)); + ExpectAndConsume( + tok::semi, diag::err_expected_after, + llvm::StringRef(DeclSpec::getSpecifierName(TagType, PPol))); PP.EnterToken(Tok); Tok.setKind(tok::semi); } @@ -1859,8 +1861,9 @@ (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) { if (Tok.isNot(tok::semi)) { const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy(); - ExpectAndConsume(tok::semi, diag::err_expected_after, - DeclSpec::getSpecifierName(TagType, PPol)); + ExpectAndConsume( + tok::semi, diag::err_expected_after, + llvm::StringRef(DeclSpec::getSpecifierName(TagType, PPol))); // Push this token back into the preprocessor and change our current token // to ';' so that the rest of the code recovers as though there were an // ';' after the definition. @@ -2234,7 +2237,8 @@ if (!(Function.TypeQuals & TypeQual)) { std::string Name(FixItName); Name += " "; - Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name.c_str()); + Insertion = FixItHint::CreateInsertion( + VS.getFirstLocation(), llvm::StringRef(Name.c_str())); Function.TypeQuals |= TypeQual; *QualifierLoc = SpecLoc.getRawEncoding(); } @@ -2258,7 +2262,8 @@ SourceLocation RefQualifierLoc; if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) { const char *Name = (RefQualifierIsLValueRef ? "& " : "&& "); - FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name); + FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), + llvm::StringRef(Name)); Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef; Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding(); @@ -3514,7 +3519,8 @@ const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)"; P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range; P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated) - << Replacement << FixItHint::CreateReplacement(Range, Replacement); + << Replacement + << FixItHint::CreateReplacement(Range, llvm::StringRef(Replacement)); } } Index: clang/lib/Parse/ParseExpr.cpp =================================================================== --- clang/lib/Parse/ParseExpr.cpp +++ clang/lib/Parse/ParseExpr.cpp @@ -334,7 +334,8 @@ } Diag(Tok, diag::err_expected) - << tok::colon << FixItHint::CreateInsertion(FILoc, FIText); + << tok::colon + << FixItHint::CreateInsertion(FILoc, llvm::StringRef(FIText)); Diag(OpToken, diag::note_matching) << tok::question; ColonLoc = Tok.getLocation(); } @@ -2213,7 +2214,7 @@ tok::kw___bridge_retain)); if (BridgeCast && !getLangOpts().ObjCAutoRefCount) { if (!TryConsumeToken(tok::kw___bridge)) { - StringRef BridgeCastName = Tok.getName(); + StringRef BridgeCastName = llvm::StringRef(Tok.getName()); SourceLocation BridgeKeywordLoc = ConsumeToken(); if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc)) Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc) Index: clang/lib/Parse/ParseExprCXX.cpp =================================================================== --- clang/lib/Parse/ParseExprCXX.cpp +++ clang/lib/Parse/ParseExprCXX.cpp @@ -1374,7 +1374,8 @@ FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true); } - if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName)) + if (ExpectAndConsume(tok::less, diag::err_expected_less_after, + llvm::StringRef(CastName))) return ExprError(); // Parse the common declaration-specifiers piece. Index: clang/lib/Parse/ParseObjc.cpp =================================================================== --- clang/lib/Parse/ParseObjc.cpp +++ clang/lib/Parse/ParseObjc.cpp @@ -1036,7 +1036,8 @@ case tok::caretequal: { std::string ThisTok(PP.getSpelling(Tok)); if (isLetter(ThisTok[0])) { - IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data()); + IdentifierInfo *II = + &PP.getIdentifierTable().get(llvm::StringRef(ThisTok.data())); Tok.setKind(tok::identifier); SelectorLoc = ConsumeToken(); return II; @@ -2877,8 +2878,9 @@ } if (str) { SourceLocation kwLoc = Tok.getLocation(); - return ExprError(Diag(AtLoc, diag::err_unexpected_at) << - FixItHint::CreateReplacement(kwLoc, str)); + return ExprError( + Diag(AtLoc, diag::err_unexpected_at) + << FixItHint::CreateReplacement(kwLoc, llvm::StringRef(str))); } else return ExprError(Diag(AtLoc, diag::err_unexpected_at)); Index: clang/lib/Parse/ParseOpenMP.cpp =================================================================== --- clang/lib/Parse/ParseOpenMP.cpp +++ clang/lib/Parse/ParseOpenMP.cpp @@ -1268,7 +1268,8 @@ SourceLocation LLoc = Tok.getLocation(); SourceLocation RLoc; - ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc); + ExprResult Val = + ParseOpenMPParensExpr(llvm::StringRef(getOpenMPClauseName(Kind)), RLoc); if (Val.isInvalid()) return nullptr; Index: clang/lib/Parse/ParsePragma.cpp =================================================================== --- clang/lib/Parse/ParsePragma.cpp +++ clang/lib/Parse/ParsePragma.cpp @@ -130,7 +130,8 @@ }; struct PragmaMSPragma : public PragmaHandler { - explicit PragmaMSPragma(const char *name) : PragmaHandler(name) {} + explicit PragmaMSPragma(const char *name) + : PragmaHandler(llvm::StringRef(name)) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; @@ -152,7 +153,8 @@ }; struct PragmaUnrollHintHandler : public PragmaHandler { - PragmaUnrollHintHandler(const char *name) : PragmaHandler(name) {} + PragmaUnrollHintHandler(const char *name) + : PragmaHandler(llvm::StringRef(name)) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; Index: clang/lib/Parse/ParseStmt.cpp =================================================================== --- clang/lib/Parse/ParseStmt.cpp +++ clang/lib/Parse/ParseStmt.cpp @@ -383,7 +383,8 @@ // If the result was valid, then we do want to diagnose this. Use // ExpectAndConsume to emit the diagnostic, even though we know it won't // succeed. - ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError); + ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, + llvm::StringRef(SemiError)); // Skip until we see a } or ;, but don't eat it. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); } Index: clang/lib/Parse/ParseTemplate.cpp =================================================================== --- clang/lib/Parse/ParseTemplate.cpp +++ clang/lib/Parse/ParseTemplate.cpp @@ -807,8 +807,8 @@ // A hint to put a space between the '>>'s. In order to make the hint as // clear as possible, we include the characters either side of the space in // the replacement, rather than just inserting a space at SecondCharLoc. - FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange, - ReplacementStr); + FixItHint Hint1 = FixItHint::CreateReplacement( + ReplacementRange, llvm::StringRef(ReplacementStr)); // A hint to put another space after the token, if it would otherwise be // lexed differently. Index: clang/lib/Parse/Parser.cpp =================================================================== --- clang/lib/Parse/Parser.cpp +++ clang/lib/Parse/Parser.cpp @@ -140,7 +140,8 @@ { DiagnosticBuilder DB = Diag(Loc, DiagID); DB << FixItHint::CreateReplacement( - SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok)); + SourceRange(Loc), + llvm::StringRef(tok::getPunctuatorSpelling(ExpectedTok))); if (DiagID == diag::err_expected) DB << ExpectedTok; else if (DiagID == diag::err_expected_after) @@ -161,7 +162,8 @@ DiagnosticBuilder DB = Spelling - ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling) + ? Diag(EndLoc, DiagID) + << FixItHint::CreateInsertion(EndLoc, llvm::StringRef(Spelling)) : Diag(Tok, DiagID); if (DiagID == diag::err_expected) DB << ExpectedTok; @@ -1176,8 +1178,9 @@ Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) << Delete; SkipUntil(tok::semi); - } else if (ExpectAndConsume(tok::semi, diag::err_expected_after, - Delete ? "delete" : "default")) { + } else if (ExpectAndConsume( + tok::semi, diag::err_expected_after, + llvm::StringRef(Delete ? "delete" : "default"))) { SkipUntil(tok::semi); } @@ -2204,7 +2207,7 @@ const char *Msg, tok::TokenKind SkipToTok) { LOpen = P.Tok.getLocation(); - if (P.ExpectAndConsume(Kind, DiagID, Msg)) { + if (P.ExpectAndConsume(Kind, DiagID, llvm::StringRef(Msg))) { if (SkipToTok != tok::unknown) P.SkipUntil(SkipToTok, Parser::StopAtSemi); return true; Index: clang/lib/Rewrite/HTMLRewrite.cpp =================================================================== --- clang/lib/Rewrite/HTMLRewrite.cpp +++ clang/lib/Rewrite/HTMLRewrite.cpp @@ -58,8 +58,8 @@ const char *BufferStart, const char *StartTag, const char *EndTag) { // Insert the tag at the absolute start/end of the range. - RB.InsertTextAfter(B, StartTag); - RB.InsertTextBefore(E, EndTag); + RB.InsertTextAfter(B, llvm::StringRef(StartTag)); + RB.InsertTextBefore(E, llvm::StringRef(EndTag)); // Scan the range to see if there is a \r or \n. If so, and if the line is // not blank, insert tags on that line as well. @@ -73,7 +73,7 @@ // Okay, we found a newline in the range. If we have an open tag, we need // to insert a close tag at the first non-whitespace before the newline. if (HadOpenTag) - RB.InsertTextBefore(LastNonWhiteSpace+1, EndTag); + RB.InsertTextBefore(LastNonWhiteSpace + 1, llvm::StringRef(EndTag)); // Instead of inserting an open tag immediately after the newline, we // wait until we see a non-whitespace character. This prevents us from @@ -92,7 +92,7 @@ default: // If there is no tag open, do it now. if (!HadOpenTag) { - RB.InsertTextAfter(i, StartTag); + RB.InsertTextAfter(i, llvm::StringRef(StartTag)); HadOpenTag = true; } Index: clang/lib/Sema/AnalysisBasedWarnings.cpp =================================================================== --- clang/lib/Sema/AnalysisBasedWarnings.cpp +++ clang/lib/Sema/AnalysisBasedWarnings.cpp @@ -761,7 +761,8 @@ BO->getOperatorLoc())); else // false && y -> false, true || y -> true. - Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr); + Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), + llvm::StringRef(FixitStr)); break; } @@ -771,7 +772,7 @@ Str = "while"; Range = cast(Term)->getCond()->getSourceRange(); RemoveDiagKind = 1; - Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); + Fixit1 = FixItHint::CreateReplacement(Range, llvm::StringRef(FixitStr)); break; case Stmt::ForStmtClass: DiagKind = 1; @@ -781,7 +782,7 @@ if (I->Output) Fixit1 = FixItHint::CreateRemoval(Range); else - Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); + Fixit1 = FixItHint::CreateReplacement(Range, llvm::StringRef(FixitStr)); break; case Stmt::CXXForRangeStmtClass: if (I->Output == 1) { @@ -801,7 +802,7 @@ Str = "do"; Range = cast(Term)->getCond()->getSourceRange(); RemoveDiagKind = 1; - Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); + Fixit1 = FixItHint::CreateReplacement(Range, llvm::StringRef(FixitStr)); break; // "switch case is taken". @@ -1090,7 +1091,8 @@ if (MacroName.empty() && !PreferClangAttr) MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens); if (MacroName.empty()) - MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]"; + MacroName = llvm::StringRef(PreferClangAttr ? "[[clang::fallthrough]]" + : "[[fallthrough]]"); return MacroName; } Index: clang/lib/Sema/CodeCompleteConsumer.cpp =================================================================== --- clang/lib/Sema/CodeCompleteConsumer.cpp +++ clang/lib/Sema/CodeCompleteConsumer.cpp @@ -319,8 +319,8 @@ OS << cast(CurDC)->getName(); } } - - CachedParentName = AllocatorRef->CopyString(OS.str()); + + CachedParentName = llvm::StringRef(AllocatorRef->CopyString(OS.str())); } return CachedParentName; @@ -617,11 +617,11 @@ std::string &Saved) { switch (R.Kind) { case CodeCompletionResult::RK_Keyword: - return R.Keyword; - + return llvm::StringRef(R.Keyword); + case CodeCompletionResult::RK_Pattern: - return R.Pattern->getTypedText(); - + return llvm::StringRef(R.Pattern->getTypedText()); + case CodeCompletionResult::RK_Macro: return R.Macro->getName(); Index: clang/lib/Sema/DeclSpec.cpp =================================================================== --- clang/lib/Sema/DeclSpec.cpp +++ clang/lib/Sema/DeclSpec.cpp @@ -1207,14 +1207,14 @@ FixItHint StorageHint, ThreadHint; if (DeclSpec::SCS SC = getStorageClassSpec()) { - SpecName = getSpecifierName(SC); + SpecName = llvm::StringRef(getSpecifierName(SC)); SCLoc = getStorageClassSpecLoc(); StorageHint = FixItHint::CreateRemoval(SCLoc); } if (DeclSpec::TSCS TSC = getThreadStorageClassSpec()) { if (!SpecName.empty()) SpecName += " "; - SpecName += getSpecifierName(TSC); + SpecName += llvm::StringRef(getSpecifierName(TSC)); SCLoc = getThreadStorageClassSpecLoc(); ThreadHint = FixItHint::CreateRemoval(SCLoc); } Index: clang/lib/Sema/SemaChecking.cpp =================================================================== --- clang/lib/Sema/SemaChecking.cpp +++ clang/lib/Sema/SemaChecking.cpp @@ -4630,8 +4630,9 @@ getSpecifierRange(startSpecifier, specifierLen)); S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) - << FixedLM->toString() - << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); + << FixedLM->toString() + << FixItHint::CreateReplacement(LMRange, + llvm::StringRef(FixedLM->toString())); } else { FixItHint Hint; @@ -4664,8 +4665,9 @@ getSpecifierRange(startSpecifier, specifierLen)); S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) - << FixedLM->toString() - << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); + << FixedLM->toString() + << FixItHint::CreateReplacement(LMRange, + llvm::StringRef(FixedLM->toString())); } else { EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) @@ -4692,8 +4694,9 @@ CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) - << FixedCS->toString() - << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); + << FixedCS->toString() + << FixItHint::CreateReplacement(CSRange, + llvm::StringRef(FixedCS->toString())); } else { EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString() << /*conversion specifier*/1, @@ -8303,7 +8306,7 @@ SmallString<16> PrettyTargetValue; if (IsBool) - PrettyTargetValue = Value.isZero() ? "false" : "true"; + PrettyTargetValue = llvm::StringRef(Value.isZero() ? "false" : "true"); else IntegerValue.toString(PrettyTargetValue); Index: clang/lib/Sema/SemaCodeComplete.cpp =================================================================== --- clang/lib/Sema/SemaCodeComplete.cpp +++ clang/lib/Sema/SemaCodeComplete.cpp @@ -2619,12 +2619,12 @@ PDecl->getIdentifier() != M->getIdentifier()) { if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(M)) { - Result.addBriefComment(RC->getBriefText(Ctx)); + Result.addBriefComment(llvm::StringRef(RC->getBriefText(Ctx))); Pattern->BriefComment = Result.getBriefComment(); } else if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl)) { - Result.addBriefComment(RC->getBriefText(Ctx)); + Result.addBriefComment(llvm::StringRef(RC->getBriefText(Ctx))); Pattern->BriefComment = Result.getBriefComment(); } } @@ -2688,13 +2688,13 @@ if (IncludeBriefComments) { // Add documentation comment, if it exists. if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) { - Result.addBriefComment(RC->getBriefText(Ctx)); + Result.addBriefComment(llvm::StringRef(RC->getBriefText(Ctx))); } else if (const ObjCMethodDecl *OMD = dyn_cast(ND)) if (OMD->isPropertyAccessor()) if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl)) - Result.addBriefComment(RC->getBriefText(Ctx)); + Result.addBriefComment(llvm::StringRef(RC->getBriefText(Ctx))); } if (StartsNestedNameSpecifier) { @@ -2978,7 +2978,8 @@ if (IncludeBriefComments && CurrentArg < FDecl->getNumParams()) if (auto RC = S.getASTContext().getRawCommentForAnyRedecl( FDecl->getParamDecl(CurrentArg))) - Result.addBriefComment(RC->getBriefText(S.getASTContext())); + Result.addBriefComment( + llvm::StringRef(RC->getBriefText(S.getASTContext()))); AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result); Result.AddTextChunk( Result.getAllocator().CopyString(FDecl->getNameAsString())); Index: clang/lib/Sema/SemaDecl.cpp =================================================================== --- clang/lib/Sema/SemaDecl.cpp +++ clang/lib/Sema/SemaDecl.cpp @@ -2289,9 +2289,10 @@ AttrSpellingListIndex, IA->getSemanticSpelling()); else if (const auto *AA = dyn_cast(Attr)) - NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), - &S.Context.Idents.get(AA->getSpelling()), - AttrSpellingListIndex); + NewAttr = S.mergeAlwaysInlineAttr( + D, AA->getRange(), + &S.Context.Idents.get(llvm::StringRef(AA->getSpelling())), + AttrSpellingListIndex); else if (S.getLangOpts().CUDA && isa(D) && (isa(Attr) || isa(Attr) || isa(Attr))) { @@ -2305,12 +2306,13 @@ else if (const auto *InternalLinkageA = dyn_cast(Attr)) NewAttr = S.mergeInternalLinkageAttr( D, InternalLinkageA->getRange(), - &S.Context.Idents.get(InternalLinkageA->getSpelling()), + &S.Context.Idents.get(llvm::StringRef(InternalLinkageA->getSpelling())), AttrSpellingListIndex); else if (const auto *CommonA = dyn_cast(Attr)) - NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), - &S.Context.Idents.get(CommonA->getSpelling()), - AttrSpellingListIndex); + NewAttr = S.mergeCommonAttr( + D, CommonA->getRange(), + &S.Context.Idents.get(llvm::StringRef(CommonA->getSpelling())), + AttrSpellingListIndex); else if (isa(Attr)) // AlignedAttrs are handled separately, because we need to handle all // such attributes on a declaration at the same time. @@ -12053,11 +12055,9 @@ if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) fmt = "NSString"; - FD->addAttr(FormatAttr::CreateImplicit(Context, - &Context.Idents.get(fmt), - FormatIdx+1, - HasVAListArg ? 0 : FormatIdx+2, - FD->getLocation())); + FD->addAttr(FormatAttr::CreateImplicit( + Context, &Context.Idents.get(llvm::StringRef(fmt)), FormatIdx + 1, + HasVAListArg ? 0 : FormatIdx + 2, FD->getLocation())); } } if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, Index: clang/lib/Sema/SemaDeclAttr.cpp =================================================================== --- clang/lib/Sema/SemaDeclAttr.cpp +++ clang/lib/Sema/SemaDeclAttr.cpp @@ -2669,7 +2669,7 @@ // TargetCodeGenInfo hook here to do validation. void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) { for (auto Str : {"tune=", "fpmath="}) - if (AttrStr.find(Str) != StringRef::npos) + if (AttrStr.find(llvm::StringRef(Str)) != StringRef::npos) Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str; } Index: clang/lib/Sema/SemaDeclCXX.cpp =================================================================== --- clang/lib/Sema/SemaDeclCXX.cpp +++ clang/lib/Sema/SemaDeclCXX.cpp @@ -703,11 +703,12 @@ SmallVector BadSpecifiers; SmallVector BadSpecifierLocs; if (auto SCS = DS.getStorageClassSpec()) { - BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); + BadSpecifiers.push_back(llvm::StringRef(DeclSpec::getSpecifierName(SCS))); BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); } if (auto TSCS = DS.getThreadStorageClassSpec()) { - BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); + BadSpecifiers.push_back( + llvm::StringRef(DeclSpec::getSpecifierName(TSCS))); BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); } if (DS.isConstexprSpecified()) { @@ -7672,7 +7673,7 @@ = Constructor->getParamDecl(0)->getIdentifier() ? "const &" : " const &"; Diag(ParamLoc, diag::err_constructor_byvalue_arg) - << FixItHint::CreateInsertion(ParamLoc, ConstRef); + << FixItHint::CreateInsertion(ParamLoc, llvm::StringRef(ConstRef)); // FIXME: Rather that making the constructor invalid, we should endeavor // to fix the type. @@ -10608,9 +10609,9 @@ E->isRecordType() && E->getAs()->getDecl()->hasObjectMember(); // Create a reference to the __builtin_objc_memmove_collectable function - StringRef MemCpyName = NeedsCollectableMemCpy ? - "__builtin_objc_memmove_collectable" : - "__builtin_memcpy"; + StringRef MemCpyName = llvm::StringRef( + NeedsCollectableMemCpy ? "__builtin_objc_memmove_collectable" + : "__builtin_memcpy"); LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, Sema::LookupOrdinaryName); S.LookupName(R, S.TUScope, true); Index: clang/lib/Sema/SemaDeclObjC.cpp =================================================================== --- clang/lib/Sema/SemaDeclObjC.cpp +++ clang/lib/Sema/SemaDeclObjC.cpp @@ -810,10 +810,10 @@ case ObjCTypeParamVariance::Covariant: case ObjCTypeParamVariance::Contravariant: { - StringRef newVarianceStr - = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant - ? "__covariant" - : "__contravariant"; + StringRef newVarianceStr = llvm::StringRef( + prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant + ? "__covariant" + : "__contravariant"); if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant) { diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(), Index: clang/lib/Sema/SemaExpr.cpp =================================================================== --- clang/lib/Sema/SemaExpr.cpp +++ clang/lib/Sema/SemaExpr.cpp @@ -9085,9 +9085,10 @@ CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); S.Diag(Loc, diag::note_objc_literal_comparison_isequal) - << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") - << FixItHint::CreateReplacement(OpRange, " isEqual:") - << FixItHint::CreateInsertion(End, "]"); + << FixItHint::CreateInsertion( + Start, llvm::StringRef(Opc == BO_EQ ? "[" : "![")) + << FixItHint::CreateReplacement(OpRange, " isEqual:") + << FixItHint::CreateInsertion(End, "]"); } } @@ -10240,8 +10241,9 @@ Diag(LHS->getLocStart(), diag::note_cast_to_void) << LHS->getSourceRange() << FixItHint::CreateInsertion(LHS->getLocStart(), - LangOpts.CPlusPlus ? "static_cast(" - : "(void)(") + llvm::StringRef(LangOpts.CPlusPlus + ? "static_cast(" + : "(void)(")) << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), ")"); } Index: clang/lib/Sema/SemaExprObjC.cpp =================================================================== --- clang/lib/Sema/SemaExprObjC.cpp +++ clang/lib/Sema/SemaExprObjC.cpp @@ -3399,8 +3399,8 @@ char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) BridgeCall += ' '; - - BridgeCall += CFBridgeName; + + BridgeCall += llvm::StringRef(CFBridgeName); DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall)); } return; @@ -3418,7 +3418,7 @@ if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) BridgeCall += ' '; - BridgeCall += CFBridgeName; + BridgeCall += llvm::StringRef(CFBridgeName); if (isa(castedE)) { DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), @@ -3435,7 +3435,8 @@ } if (CCK == Sema::CCK_CStyleCast) { - DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword)); + DiagB.AddFixItHint(FixItHint::CreateInsertion( + afterLParen, llvm::StringRef(bridgeKeyword))); } else if (CCK == Sema::CCK_OtherCast) { if (const CXXNamedCastExpr *NCE = dyn_cast(realCast)) { std::string castCode = "("; Index: clang/lib/Sema/SemaLookup.cpp =================================================================== --- clang/lib/Sema/SemaLookup.cpp +++ clang/lib/Sema/SemaLookup.cpp @@ -4341,7 +4341,7 @@ const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs); for (unsigned I = 0; I != NumCTypeSpecs; ++I) - Consumer.addKeywordResult(CTypeSpecs[I]); + Consumer.addKeywordResult(llvm::StringRef(CTypeSpecs[I])); if (SemaRef.getLangOpts().C99) Consumer.addKeywordResult("restrict"); @@ -4372,7 +4372,7 @@ "signed", "unsigned", "void" }; for (auto *kw : CastableTypeSpecs) - Consumer.addKeywordResult(kw); + Consumer.addKeywordResult(llvm::StringRef(kw)); } if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) { @@ -4395,7 +4395,7 @@ }; const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs); for (unsigned I = 0; I != NumCXXExprs; ++I) - Consumer.addKeywordResult(CXXExprs[I]); + Consumer.addKeywordResult(llvm::StringRef(CXXExprs[I])); if (isa(SemaRef.CurContext) && cast(SemaRef.CurContext)->isInstance()) @@ -4421,7 +4421,7 @@ "do", "else", "for", "goto", "if", "return", "switch", "while" }; const unsigned NumCStmts = llvm::array_lengthof(CStmts); for (unsigned I = 0; I != NumCStmts; ++I) - Consumer.addKeywordResult(CStmts[I]); + Consumer.addKeywordResult(llvm::StringRef(CStmts[I])); if (SemaRef.getLangOpts().CPlusPlus) { Consumer.addKeywordResult("catch"); Index: clang/lib/Sema/SemaObjCProperty.cpp =================================================================== --- clang/lib/Sema/SemaObjCProperty.cpp +++ clang/lib/Sema/SemaObjCProperty.cpp @@ -330,7 +330,8 @@ Token Tok; do { lexer.LexFromRawLexer(Tok); - if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == attrName) { + if (Tok.is(tok::raw_identifier) && + Tok.getRawIdentifier() == llvm::StringRef(attrName)) { Loc = Tok.getLocation(); return true; } @@ -2013,8 +2014,8 @@ // @property () ... case. SourceLocation AfterLParen = getLocForEndOfToken(Property->getLParenLoc()); - StringRef NonatomicStr = AttributesAsWritten? "nonatomic, " - : "nonatomic"; + StringRef NonatomicStr = llvm::StringRef( + AttributesAsWritten ? "nonatomic, " : "nonatomic"); Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) << FixItHint::CreateInsertion(AfterLParen, NonatomicStr); Index: clang/lib/Sema/SemaOpenMP.cpp =================================================================== --- clang/lib/Sema/SemaOpenMP.cpp +++ clang/lib/Sema/SemaOpenMP.cpp @@ -1598,8 +1598,8 @@ QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); Sema::CapturedParamNameType Params[] = { - std::make_pair(".global_tid.", KmpInt32PtrTy), - std::make_pair(".bound_tid.", KmpInt32PtrTy), + std::make_pair(StringRef(".global_tid."), KmpInt32PtrTy), + std::make_pair(StringRef(".bound_tid."), KmpInt32PtrTy), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, @@ -1638,12 +1638,13 @@ EPI.Variadic = true; QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); Sema::CapturedParamNameType Params[] = { - std::make_pair(".global_tid.", KmpInt32Ty), - std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), - std::make_pair(".privates.", Context.VoidPtrTy.withConst()), - std::make_pair(".copy_fn.", + std::make_pair(StringRef(".global_tid."), KmpInt32Ty), + std::make_pair(StringRef(".part_id."), + Context.getPointerType(KmpInt32Ty)), + std::make_pair(StringRef(".privates."), Context.VoidPtrTy.withConst()), + std::make_pair(StringRef(".copy_fn."), Context.getPointerType(CopyFnType).withConst()), - std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), + std::make_pair(StringRef(".task_t."), Context.VoidPtrTy.withConst()), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, @@ -1668,17 +1669,19 @@ EPI.Variadic = true; QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); Sema::CapturedParamNameType Params[] = { - std::make_pair(".global_tid.", KmpInt32Ty), - std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), - std::make_pair(".privates.", + std::make_pair(StringRef(".global_tid."), KmpInt32Ty), + std::make_pair(StringRef(".part_id."), + Context.getPointerType(KmpInt32Ty)), + std::make_pair(StringRef(".privates."), Context.VoidPtrTy.withConst().withRestrict()), std::make_pair( - ".copy_fn.", + StringRef(".copy_fn."), Context.getPointerType(CopyFnType).withConst().withRestrict()), - std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), - std::make_pair(".lb.", KmpUInt64Ty), - std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), - std::make_pair(".liter.", KmpInt32Ty), + std::make_pair(StringRef(".task_t."), Context.VoidPtrTy.withConst()), + std::make_pair(StringRef(".lb."), KmpUInt64Ty), + std::make_pair(StringRef(".ub."), KmpUInt64Ty), + std::make_pair(StringRef(".st."), KmpInt64Ty), + std::make_pair(StringRef(".liter."), KmpInt32Ty), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, @@ -1698,10 +1701,10 @@ QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); Sema::CapturedParamNameType Params[] = { - std::make_pair(".global_tid.", KmpInt32PtrTy), - std::make_pair(".bound_tid.", KmpInt32PtrTy), - std::make_pair(".previous.lb.", Context.getSizeType()), - std::make_pair(".previous.ub.", Context.getSizeType()), + std::make_pair(StringRef(".global_tid."), KmpInt32PtrTy), + std::make_pair(StringRef(".bound_tid."), KmpInt32PtrTy), + std::make_pair(StringRef(".previous.lb."), Context.getSizeType()), + std::make_pair(StringRef(".previous.ub."), Context.getSizeType()), std::make_pair(StringRef(), QualType()) // __context with shared vars }; ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, Index: clang/lib/Sema/SemaStmt.cpp =================================================================== --- clang/lib/Sema/SemaStmt.cpp +++ clang/lib/Sema/SemaStmt.cpp @@ -1925,7 +1925,8 @@ VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, const char *Name) { DeclContext *DC = SemaRef.CurContext; - IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); + IdentifierInfo *II = + &SemaRef.PP.getIdentifierTable().get(llvm::StringRef(Name)); TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp =================================================================== --- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp +++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp @@ -2628,7 +2628,7 @@ /*S=*/nullptr, NewDRD); const char *Names[] = {"omp_in", "omp_out"}; for (auto &Name : Names) { - DeclarationName DN(&SemaRef.Context.Idents.get(Name)); + DeclarationName DN(&SemaRef.Context.Idents.get(llvm::StringRef(Name))); auto OldLookup = D->lookup(DN); auto Lookup = NewDRD->lookup(DN); if (!OldLookup.empty() && !Lookup.empty()) { @@ -2645,7 +2645,7 @@ /*S=*/nullptr, NewDRD); const char *Names[] = {"omp_orig", "omp_priv"}; for (auto &Name : Names) { - DeclarationName DN(&SemaRef.Context.Idents.get(Name)); + DeclarationName DN(&SemaRef.Context.Idents.get(llvm::StringRef(Name))); auto OldLookup = D->lookup(DN); auto Lookup = NewDRD->lookup(DN); if (!OldLookup.empty() && !Lookup.empty()) { Index: clang/lib/Sema/SemaType.cpp =================================================================== --- clang/lib/Sema/SemaType.cpp +++ clang/lib/Sema/SemaType.cpp @@ -2680,7 +2680,7 @@ for (auto &E : QualKinds) { if (Quals & E.Mask) { if (!QualStr.empty()) QualStr += ' '; - QualStr += E.Name; + QualStr += llvm::StringRef(E.Name); // If we have a location for the qualifier, offer a fixit. SourceLocation QualLoc = E.Loc; @@ -4626,7 +4626,7 @@ } IdentifierLoc *Arg = new (S.Context) IdentifierLoc; - Arg->Ident = &S.Context.Idents.get(attrStr); + Arg->Ident = &S.Context.Idents.get(llvm::StringRef(attrStr)); Arg->Loc = SourceLocation(); ArgsUnion Args(Arg); Index: clang/lib/Serialization/ASTReader.cpp =================================================================== --- clang/lib/Serialization/ASTReader.cpp +++ clang/lib/Serialization/ASTReader.cpp @@ -517,7 +517,7 @@ if (MacroNames && !Macros.count(MacroName)) MacroNames->push_back(MacroName); - Macros[MacroName] = std::make_pair("", true); + Macros[MacroName] = std::make_pair(StringRef(""), true); continue; } @@ -1374,7 +1374,7 @@ IncludeLoc = getImportLocation(F); } - auto Buffer = ReadBuffer(SLocEntryCursor, Name); + auto Buffer = ReadBuffer(SLocEntryCursor, llvm::StringRef(Name)); if (!Buffer) return true; SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID, @@ -1399,17 +1399,17 @@ std::pair ASTReader::getModuleImportLoc(int ID) { if (ID == 0) - return std::make_pair(SourceLocation(), ""); + return std::make_pair(SourceLocation(), StringRef("")); if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) { Error("source location entry ID out-of-range for AST file"); - return std::make_pair(SourceLocation(), ""); + return std::make_pair(SourceLocation(), StringRef("")); } // Find which module file this entry lands in. ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second; if (!M->isModule()) - return std::make_pair(SourceLocation(), ""); + return std::make_pair(SourceLocation(), StringRef("")); // FIXME: Can we map this down to a particular submodule? That would be // ideal. @@ -1633,7 +1633,7 @@ internal_key_type ikey; ikey.Size = off_t(endian::readNext(d)); ikey.ModTime = time_t(endian::readNext(d)); - ikey.Filename = (const char *)d; + ikey.Filename = llvm::StringRef((const char *)d); ikey.Imported = true; return ikey; } Index: clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp +++ clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp @@ -41,7 +41,7 @@ class APIMisuse : public BugType { public: APIMisuse(const CheckerBase *checker, const char *name) - : BugType(checker, name, "API Misuse (Apple)") {} + : BugType(checker, llvm::StringRef(name), "API Misuse (Apple)") {} }; } // end anonymous namespace @@ -141,7 +141,7 @@ if (State->isNull(C.getSVal(E)).isConstrainedTrue()) { if (ExplodedNode *N = C.generateErrorNode()) { - generateBugReport(N, Msg, E->getSourceRange(), E, C); + generateBugReport(N, llvm::StringRef(Msg), E->getSourceRange(), E, C); } } } @@ -592,7 +592,7 @@ if (!N) return; - const char *description; + StringRef description; if (FuncII == Retain) description = "Null pointer argument in call to CFRetain"; else if (FuncII == Release) Index: clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp @@ -247,7 +247,7 @@ if (!BT_Null) BT_Null.reset(new BuiltinBug( - Filter.CheckNameCStringNullArg, categories::UnixAPI, + Filter.CheckNameCStringNullArg, llvm::StringRef(categories::UnixAPI), "Null pointer argument in call to byte string function")); SmallString<80> buf; @@ -318,7 +318,7 @@ // Generate a report for this bug. std::unique_ptr report; if (warningMsg) { - report = llvm::make_unique(*BT, warningMsg, N); + report = llvm::make_unique(*BT, StringRef(warningMsg), N); } else { assert(CurrentFunctionDescription); assert(CurrentFunctionDescription[0] != '\0'); @@ -543,7 +543,8 @@ if (!BT_Overlap) BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap, - categories::UnixAPI, "Improper arguments")); + llvm::StringRef(categories::UnixAPI), + "Improper arguments")); // Generate a report for this bug. auto report = llvm::make_unique( @@ -609,9 +610,9 @@ // This isn't a great error message, but this should never occur in real // code anyway -- you'd have to create a buffer longer than a size_t can // represent, which is sort of a contradiction. - const char *warning = - "This expression will create a string whose length is too big to " - "be represented as a size_t"; + StringRef warning = + "This expression will create a string whose length is too big to " + "be represented as a size_t"; // Generate a report for this bug. C.emitReport( @@ -721,9 +722,10 @@ if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) { if (!BT_NotCString) - BT_NotCString.reset(new BuiltinBug( - Filter.CheckNameCStringNotNullTerm, categories::UnixAPI, - "Argument is not a null-terminated string.")); + BT_NotCString.reset( + new BuiltinBug(Filter.CheckNameCStringNotNullTerm, + llvm::StringRef(categories::UnixAPI), + "Argument is not a null-terminated string.")); SmallString<120> buf; llvm::raw_svector_ostream os(buf); @@ -781,9 +783,10 @@ if (ExplodedNode *N = C.generateNonFatalErrorNode(state)) { if (!BT_NotCString) - BT_NotCString.reset(new BuiltinBug( - Filter.CheckNameCStringNotNullTerm, categories::UnixAPI, - "Argument is not a null-terminated string.")); + BT_NotCString.reset( + new BuiltinBug(Filter.CheckNameCStringNotNullTerm, + llvm::StringRef(categories::UnixAPI), + "Argument is not a null-terminated string.")); SmallString<120> buf; llvm::raw_svector_ostream os(buf); Index: clang/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp @@ -86,7 +86,7 @@ void LazyInit_BT(const char *desc, std::unique_ptr &BT) const { if (!BT) - BT.reset(new BuiltinBug(this, desc)); + BT.reset(new BuiltinBug(this, llvm::StringRef(desc))); } bool uninitRefOrPointer(CheckerContext &C, const SVal &V, SourceRange ArgRange, Index: clang/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp @@ -63,12 +63,13 @@ if (!OrigPointeeTy->isRecordType()) { SourceRange Sr[1] = {CE->getSourceRange()}; PathDiagnosticLocation Loc(CE, BR.getSourceManager(), AC); - BR.EmitBasicReport( - AC->getDecl(), Checker, "Cast from non-struct type to struct type", - categories::LogicError, "Casting a non-structure type to a structure " - "type and accessing a field can lead to memory " - "access errors or data corruption.", - Loc, Sr); + BR.EmitBasicReport(AC->getDecl(), Checker, + "Cast from non-struct type to struct type", + llvm::StringRef(categories::LogicError), + "Casting a non-structure type to a structure " + "type and accessing a field can lead to memory " + "access errors or data corruption.", + Loc, Sr); } else { // Don't warn when size of data is unknown. const auto *U = dyn_cast(E); @@ -92,7 +93,7 @@ PathDiagnosticLocation Loc(CE, BR.getSourceManager(), AC); BR.EmitBasicReport(AC->getDecl(), Checker, "Widening cast to struct type", - categories::LogicError, + llvm::StringRef(categories::LogicError), "Casting data to a larger structure type and accessing " "a field can lead to memory access errors or data " "corruption.", Index: clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp +++ clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp @@ -262,7 +262,8 @@ PathDiagnosticLocation DLoc = PathDiagnosticLocation::createBegin(D, BR.getSourceManager()); - BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC, + BR.EmitBasicReport(D, this, llvm::StringRef(Name), + llvm::StringRef(categories::CoreFoundationObjectiveC), OS.str(), DLoc); return; } @@ -612,8 +613,8 @@ std::unique_ptr BR( new BugReport(*MissingReleaseBugType, OS.str(), ErrNode)); - addNoteForDecl(BR, MsgDeclared, PropDecl); - addNoteForDecl(BR, MsgSynthesized, PropImpl); + addNoteForDecl(BR, llvm::StringRef(MsgDeclared), PropDecl); + addNoteForDecl(BR, llvm::StringRef(MsgSynthesized), PropImpl); C.emitReport(std::move(BR)); } @@ -740,9 +741,9 @@ new BugReport(*ExtraReleaseBugType, OS.str(), ErrNode)); BR->addRange(M.getOriginExpr()->getSourceRange()); - addNoteForDecl(BR, MsgDeclared, PropDecl); + addNoteForDecl(BR, llvm::StringRef(MsgDeclared), PropDecl); if (!ReleasedByCIFilterDealloc) - addNoteForDecl(BR, MsgSynthesized, PropImpl); + addNoteForDecl(BR, llvm::StringRef(MsgSynthesized), PropImpl); C.emitReport(std::move(BR)); @@ -793,15 +794,15 @@ MissingReleaseBugType.reset( new BugType(this, "Missing ivar release (leak)", - categories::MemoryCoreFoundationObjectiveC)); + llvm::StringRef(categories::MemoryCoreFoundationObjectiveC))); ExtraReleaseBugType.reset( new BugType(this, "Extra ivar release", - categories::MemoryCoreFoundationObjectiveC)); + llvm::StringRef(categories::MemoryCoreFoundationObjectiveC))); MistakenDeallocBugType.reset( new BugType(this, "Mistaken dealloc", - categories::MemoryCoreFoundationObjectiveC)); + llvm::StringRef(categories::MemoryCoreFoundationObjectiveC))); } void ObjCDeallocChecker::initIdentifierInfoAndSelectors( @@ -1080,8 +1081,8 @@ StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName(); const char *ReleasePrefix = "input"; - if (!(PropName.startswith(ReleasePrefix) || - IvarName.startswith(ReleasePrefix))) { + if (!(PropName.startswith(llvm::StringRef(ReleasePrefix)) || + IvarName.startswith(llvm::StringRef(ReleasePrefix)))) { return false; } Index: clang/lib/StaticAnalyzer/Checkers/CheckObjCInstMethSignature.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/CheckObjCInstMethSignature.cpp +++ clang/lib/StaticAnalyzer/Checkers/CheckObjCInstMethSignature.cpp @@ -70,9 +70,10 @@ PathDiagnosticLocation::createBegin(MethDerived, BR.getSourceManager()); - BR.EmitBasicReport( - MethDerived, Checker, "Incompatible instance method return type", - categories::CoreFoundationObjectiveC, os.str(), MethDLoc); + BR.EmitBasicReport(MethDerived, Checker, + "Incompatible instance method return type", + llvm::StringRef(categories::CoreFoundationObjectiveC), + os.str(), MethDLoc); } } Index: clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp +++ clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp @@ -292,8 +292,8 @@ PathDiagnosticLocation FSLoc = PathDiagnosticLocation::createBegin(FS, BR.getSourceManager(), AC); BR.EmitBasicReport(AC->getDecl(), filter.checkName_FloatLoopCounter, - bugType, "Security", os.str(), - FSLoc, ranges); + llvm::StringRef(bugType), "Security", os.str(), FSLoc, + ranges); } //===----------------------------------------------------------------------===// @@ -695,7 +695,8 @@ }; for (size_t i = 0; i < num_setids; i++) - II_setid[i] = &BR.getContext().Idents.get(identifiers[i]); + II_setid[i] = + &BR.getContext().Idents.get(llvm::StringRef(identifiers[i])); } const IdentifierInfo *id = FD->getIdentifier(); Index: clang/lib/StaticAnalyzer/Checkers/CheckSizeofPointer.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/CheckSizeofPointer.cpp +++ clang/lib/StaticAnalyzer/Checkers/CheckSizeofPointer.cpp @@ -66,7 +66,7 @@ PathDiagnosticLocation::createBegin(E, BR.getSourceManager(), AC); BR.EmitBasicReport(AC->getDecl(), Checker, "Potential unintended use of sizeof() on pointer type", - categories::LogicError, + llvm::StringRef(categories::LogicError), "The code calls sizeof() on a pointer type. " "This can produce an unexpected result.", ELoc, ArgEx->getSourceRange()); Index: clang/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp @@ -104,7 +104,7 @@ new BuiltinBug(this, "Conversion", "Possible loss of sign/precision.")); // Generate a report for this bug. - auto R = llvm::make_unique(*BT, Msg, N); + auto R = llvm::make_unique(*BT, StringRef(Msg), N); C.emitReport(std::move(R)); } Index: clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp @@ -201,8 +201,8 @@ return; } - BR.EmitBasicReport(AC->getDecl(), Checker, BugType, "Dead store", os.str(), - L, R); + BR.EmitBasicReport(AC->getDecl(), Checker, llvm::StringRef(BugType), + "Dead store", os.str(), L, R); } void CheckVarDecl(const VarDecl *VD, const Expr *Ex, const Expr *Val, Index: clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp +++ clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp @@ -197,7 +197,8 @@ return; BR.EmitBasicReport( - MD, Checker, "Property access", categories::CoreFoundationObjectiveC, + MD, Checker, "Property access", + llvm::StringRef(categories::CoreFoundationObjectiveC), "Direct assignment to an instance variable backing a property; " "use the setter instead", PathDiagnosticLocation(IvarRef, BR.getSourceManager(), DCtx)); Index: clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp @@ -39,7 +39,7 @@ if (!BT) BT.reset(new BuiltinBug(this, "Division by zero")); - auto R = llvm::make_unique(*BT, Msg, N); + auto R = llvm::make_unique(*BT, StringRef(Msg), N); bugreporter::trackNullOrUndefValue(N, bugreporter::GetDenomExpr(N), *R); C.emitReport(std::move(R)); } Index: clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp +++ clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp @@ -70,7 +70,8 @@ void initBugType() const { if (!ObjCGenericsBugType) ObjCGenericsBugType.reset( - new BugType(this, "Generics", categories::CoreFoundationObjectiveC)); + new BugType(this, "Generics", + llvm::StringRef(categories::CoreFoundationObjectiveC))); } class GenericsBugVisitor : public BugReporterVisitorImpl { Index: clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp @@ -119,7 +119,7 @@ if (LC->getCurrentStackFrame()->getParent() != nullptr) return; - reportBug(getArgumentValueString(CE, C), C); + reportBug(llvm::StringRef(getArgumentValueString(CE, C)), C); } void ExprInspectionChecker::analyzerWarnIfReached(const CallExpr *CE, @@ -139,7 +139,7 @@ if (LC->getCurrentStackFrame()->getParent() == nullptr) return; - reportBug(getArgumentValueString(CE, C), C); + reportBug(llvm::StringRef(getArgumentValueString(CE, C)), C); } void ExprInspectionChecker::analyzerExplain(const CallExpr *CE, Index: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp @@ -642,7 +642,7 @@ // Generate diagnostic. if (ExplodedNode *N = C.generateNonFatalErrorNode()) { initBugType(); - auto report = llvm::make_unique(*BT, Msg, N); + auto report = llvm::make_unique(*BT, StringRef(Msg), N); report->addRange(E->getSourceRange()); C.emitReport(std::move(report)); return true; Index: clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp @@ -69,10 +69,9 @@ PathDiagnosticLocation ELoc = PathDiagnosticLocation::createOperatorLoc(B, BR.getSourceManager()); - BR.EmitBasicReport(AC->getDecl(), Checker, - "Use of identical expressions", - categories::LogicError, - Message, ELoc, Sr); + BR.EmitBasicReport(AC->getDecl(), Checker, "Use of identical expressions", + llvm::StringRef(categories::LogicError), Message, ELoc, + Sr); } void FindIdenticalExprVisitor::checkBitwiseOrLogicalOp(const BinaryOperator *B, @@ -118,10 +117,10 @@ const IfStmt *InnerIf = dyn_cast(*CS->body_begin()); if (InnerIf && isIdenticalStmt(AC->getASTContext(), I->getCond(), InnerIf->getCond(), /*ignoreSideEffects=*/ false)) { PathDiagnosticLocation ELoc(InnerIf->getCond(), BR.getSourceManager(), AC); - BR.EmitBasicReport(AC->getDecl(), Checker, "Identical conditions", - categories::LogicError, - "conditions of the inner and outer statements are identical", - ELoc); + BR.EmitBasicReport( + AC->getDecl(), Checker, "Identical conditions", + llvm::StringRef(categories::LogicError), + "conditions of the inner and outer statements are identical", ELoc); } } } @@ -142,7 +141,7 @@ SourceRange Sr = Cond1->getSourceRange(); PathDiagnosticLocation ELoc(Cond2, BR.getSourceManager(), AC); BR.EmitBasicReport(AC->getDecl(), Checker, "Identical conditions", - categories::LogicError, + llvm::StringRef(categories::LogicError), "expression is identical to previous condition", ELoc, Sr); } @@ -171,9 +170,8 @@ if (isIdenticalStmt(AC->getASTContext(), Stmt1, Stmt2, true)) { PathDiagnosticLocation ELoc = PathDiagnosticLocation::createBegin(I, BR.getSourceManager(), AC); - BR.EmitBasicReport(AC->getDecl(), Checker, - "Identical branches", - categories::LogicError, + BR.EmitBasicReport(AC->getDecl(), Checker, "Identical branches", + llvm::StringRef(categories::LogicError), "true and false branches are identical", ELoc); } return true; @@ -261,7 +259,7 @@ Message = "comparison of identical expressions always evaluates to false"; BR.EmitBasicReport(AC->getDecl(), Checker, "Compare of identical expressions", - categories::LogicError, Message, ELoc); + llvm::StringRef(categories::LogicError), Message, ELoc); } } @@ -283,7 +281,7 @@ BR.EmitBasicReport( AC->getDecl(), Checker, "Identical expressions in conditional expression", - categories::LogicError, + llvm::StringRef(categories::LogicError), "identical expressions on both sides of ':' in conditional expression", ELoc, Sr); } Index: clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp @@ -545,8 +545,8 @@ PathDiagnosticLocation::createBegin(FirstIvarDecl, BR.getSourceManager()); BR.EmitBasicReport(FirstIvarDecl, CheckName, "Incomplete invalidation", - categories::CoreFoundationObjectiveC, os.str(), - IvarDecLocation); + llvm::StringRef(categories::CoreFoundationObjectiveC), + os.str(), IvarDecLocation); } void IvarInvalidationCheckerImpl:: @@ -564,13 +564,13 @@ Mgr.getAnalysisDeclContext(MethodD)); BR.EmitBasicReport(MethodD, Filter.checkName_InstanceVariableInvalidation, "Incomplete invalidation", - categories::CoreFoundationObjectiveC, os.str(), - MethodDecLocation); + llvm::StringRef(categories::CoreFoundationObjectiveC), + os.str(), MethodDecLocation); } else { BR.EmitBasicReport( IvarD, Filter.checkName_InstanceVariableInvalidation, - "Incomplete invalidation", categories::CoreFoundationObjectiveC, - os.str(), + "Incomplete invalidation", + llvm::StringRef(categories::CoreFoundationObjectiveC), os.str(), PathDiagnosticLocation::createBegin(IvarD, BR.getSourceManager())); } } Index: clang/lib/StaticAnalyzer/Checkers/LLVMConventionsChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/LLVMConventionsChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/LLVMConventionsChecker.cpp @@ -182,8 +182,9 @@ "std::string that it outlives"; PathDiagnosticLocation VDLoc = PathDiagnosticLocation::createBegin(VD, BR.getSourceManager()); - BR.EmitBasicReport(DeclWithIssue, Checker, desc, "LLVM Conventions", desc, - VDLoc, Init->getSourceRange()); + BR.EmitBasicReport(DeclWithIssue, Checker, llvm::StringRef(desc), + "LLVM Conventions", llvm::StringRef(desc), VDLoc, + Init->getSourceRange()); } //===----------------------------------------------------------------------===// Index: clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp @@ -184,7 +184,7 @@ bool IsAllocator) { for (unsigned I = 0; I < FunctionsToTrackSize; ++I) { ADFunctionInfo FI = FunctionsToTrack[I]; - if (FI.Name != Name) + if (llvm::StringRef(FI.Name) != Name) continue; // Make sure the function is of the right type (allocator vs deallocator). if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx)) Index: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -1875,8 +1875,8 @@ auto R = llvm::make_unique( *BT_DoubleFree[*CheckKind], - (Released ? "Attempt to free released memory" - : "Attempt to free non-owned memory"), + StringRef(Released ? "Attempt to free released memory" + : "Attempt to free non-owned memory"), N); R->addRange(Range); R->markInteresting(Sym); @@ -2732,7 +2732,8 @@ // Generate the extra diagnostic. PathDiagnosticLocation Pos(S, BRC.getSourceManager(), N->getLocationContext()); - return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint); + return new PathDiagnosticEventPiece(Pos, llvm::StringRef(Msg), true, + StackHint); } void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State, Index: clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp @@ -282,7 +282,7 @@ i != e; ++i) { BR.EmitBasicReport( - D, this, "malloc() size overflow", categories::UnixAPI, + D, this, "malloc() size overflow", llvm::StringRef(categories::UnixAPI), "the computation of the size of the memory allocation may overflow", PathDiagnosticLocation::createOperatorLoc(i->mulop, BR.getSourceManager()), Index: clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp @@ -239,7 +239,8 @@ BR.getSourceManager(), ADC); BR.EmitBasicReport(D, this, "Allocator sizeof operand mismatch", - categories::UnixAPI, OS.str(), L, Ranges); + llvm::StringRef(categories::UnixAPI), OS.str(), L, + Ranges); } } } Index: clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp @@ -75,7 +75,7 @@ PathDiagnosticLocation L = PathDiagnosticLocation::create(D, BR.getSourceManager()); BR.EmitBasicReport(D, this, "Bad return type when passing NSError**", - "Coding conventions (Apple)", err, L); + "Coding conventions (Apple)", llvm::StringRef(err), L); } } @@ -122,7 +122,7 @@ PathDiagnosticLocation L = PathDiagnosticLocation::create(D, BR.getSourceManager()); BR.EmitBasicReport(D, this, "Bad return type when passing CFErrorRef*", - "Coding conventions (Apple)", err, L); + "Coding conventions (Apple)", llvm::StringRef(err), L); } } Index: clang/lib/StaticAnalyzer/Checkers/ObjCContainersASTChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/ObjCContainersASTChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/ObjCContainersASTChecker.cpp @@ -143,8 +143,8 @@ PathDiagnosticLocation CELoc = PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); BR.EmitBasicReport(AC->getDecl(), Checker, OsName.str(), - categories::CoreFoundationObjectiveC, Os.str(), CELoc, - Arg->getSourceRange()); + llvm::StringRef(categories::CoreFoundationObjectiveC), + Os.str(), CELoc, Arg->getSourceRange()); } // Recurse and check children. Index: clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp @@ -34,8 +34,9 @@ mutable std::unique_ptr BT; inline void initBugType() const { if (!BT) - BT.reset(new BugType(this, "CFArray API", - categories::CoreFoundationObjectiveC)); + BT.reset( + new BugType(this, "CFArray API", + llvm::StringRef(categories::CoreFoundationObjectiveC))); } inline SymbolRef getArraySym(const Expr *E, CheckerContext &C) const { Index: clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/ObjCMissingSuperCallChecker.cpp @@ -109,7 +109,8 @@ assert(Descriptor.ArgumentCount <= 1); // No multi-argument selectors yet. // Get the selector. - IdentifierInfo *II = &Ctx.Idents.get(Descriptor.SelectorName); + IdentifierInfo *II = + &Ctx.Idents.get(llvm::StringRef(Descriptor.SelectorName)); Selector Sel = Ctx.Selectors.getSelector(Descriptor.ArgumentCount, &II); ClassSelectors.insert(Sel); @@ -206,8 +207,10 @@ << "' instance method in " << SuperclassName.str() << " subclass '" << *D << "' is missing a [super " << S.getAsString() << "] call"; - BR.EmitBasicReport(MD, this, Name, categories::CoreFoundationObjectiveC, - os.str(), DLoc); + BR.EmitBasicReport( + MD, this, llvm::StringRef(Name), + llvm::StringRef(categories::CoreFoundationObjectiveC), os.str(), + DLoc); } } } Index: clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChecker.cpp @@ -158,9 +158,10 @@ return; if (!BT) - BT.reset(new BugType(this, "Missing \"self = [(super or self) init...]\"", - categories::CoreFoundationObjectiveC)); - C.emitReport(llvm::make_unique(*BT, errorStr, N)); + BT.reset( + new BugType(this, "Missing \"self = [(super or self) init...]\"", + llvm::StringRef(categories::CoreFoundationObjectiveC))); + C.emitReport(llvm::make_unique(*BT, StringRef(errorStr), N)); } void ObjCSelfInitChecker::checkPostObjCMessage(const ObjCMethodCall &Msg, Index: clang/lib/StaticAnalyzer/Checkers/ObjCSuperDeallocChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/ObjCSuperDeallocChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/ObjCSuperDeallocChecker.cpp @@ -224,7 +224,7 @@ DoubleSuperDeallocBugType.reset( new BugType(this, "[super dealloc] should not be called more than once", - categories::CoreFoundationObjectiveC)); + llvm::StringRef(categories::CoreFoundationObjectiveC))); } void Index: clang/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp @@ -690,16 +690,16 @@ void addClassMethSummary(const char* Cls, const char* name, const RetainSummary *Summ, bool isNullary = true) { - IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); - Selector S = isNullary ? GetNullarySelector(name, Ctx) - : GetUnarySelector(name, Ctx); + IdentifierInfo *ClsII = &Ctx.Idents.get(llvm::StringRef(Cls)); + Selector S = isNullary ? GetNullarySelector(llvm::StringRef(name), Ctx) + : GetUnarySelector(llvm::StringRef(name), Ctx); ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } void addInstMethSummary(const char* Cls, const char* nullaryName, const RetainSummary *Summ) { - IdentifierInfo* ClsII = &Ctx.Idents.get(Cls); - Selector S = GetNullarySelector(nullaryName, Ctx); + IdentifierInfo *ClsII = &Ctx.Idents.get(llvm::StringRef(Cls)); + Selector S = GetNullarySelector(llvm::StringRef(nullaryName), Ctx); ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ; } @@ -712,14 +712,16 @@ void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) { va_list argp; va_start(argp, Summ); - addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp); + addMethodSummary(&Ctx.Idents.get(llvm::StringRef(Cls)), ObjCMethodSummaries, + Summ, argp); va_end(argp); } void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) { va_list argp; va_start(argp, Summ); - addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp); + addMethodSummary(&Ctx.Idents.get(llvm::StringRef(Cls)), + ObjCClassMethodSummaries, Summ, argp); va_end(argp); } @@ -1659,7 +1661,9 @@ class CFRefBug : public BugType { protected: CFRefBug(const CheckerBase *checker, StringRef name) - : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {} + : BugType(checker, name, + llvm::StringRef(categories::MemoryCoreFoundationObjectiveC)) { + } public: @@ -1799,7 +1803,7 @@ CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled, const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, bool registerVisitor = true) - : BugReport(D, D.getDescription(), n) { + : BugReport(D, llvm::StringRef(D.getDescription()), n) { if (registerVisitor) addVisitor(llvm::make_unique(sym, GCEnabled, Log)); addGCModeDescription(LOpts, GCEnabled); @@ -1808,7 +1812,7 @@ CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled, const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym, StringRef endText) - : BugReport(D, D.getDescription(), endText, n) { + : BugReport(D, llvm::StringRef(D.getDescription()), endText, n) { addVisitor(llvm::make_unique(sym, GCEnabled, Log)); addGCModeDescription(LOpts, GCEnabled); } @@ -1866,7 +1870,7 @@ } assert(GCModeDescription && "invalid/unknown GC mode"); - addExtraText(GCModeDescription); + addExtraText(llvm::StringRef(GCModeDescription)); } static bool isNumericLiteralExpression(const Expr *E) { Index: clang/lib/StaticAnalyzer/Checkers/SelectorExtras.h =================================================================== --- clang/lib/StaticAnalyzer/Checkers/SelectorExtras.h +++ clang/lib/StaticAnalyzer/Checkers/SelectorExtras.h @@ -20,10 +20,10 @@ const char *First, va_list argp) { SmallVector II; - II.push_back(&Ctx.Idents.get(First)); + II.push_back(&Ctx.Idents.get(StringRef(First))); while (const char *s = va_arg(argp, const char *)) - II.push_back(&Ctx.Idents.get(s)); + II.push_back(&Ctx.Idents.get(StringRef(s))); return Ctx.Selectors.getSelector(II.size(), &II[0]); } @@ -59,7 +59,7 @@ const char *Name) { if (!Sel.isNull()) return; - Sel = GetNullarySelector(Name, Ctx); + Sel = GetNullarySelector(StringRef(Name), Ctx); } } // end namespace ento Index: clang/lib/StaticAnalyzer/Checkers/UndefinedAssignmentChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/UndefinedAssignmentChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/UndefinedAssignmentChecker.cpp @@ -54,7 +54,7 @@ const char *str = "Assigned value is garbage or undefined"; if (!BT) - BT.reset(new BuiltinBug(this, str)); + BT.reset(new BuiltinBug(this, llvm::StringRef(str))); // Generate a report for this bug. const Expr *ex = nullptr; @@ -83,7 +83,7 @@ break; } - auto R = llvm::make_unique(*BT, str, N); + auto R = llvm::make_unique(*BT, StringRef(str), N); if (ex) { R->addRange(ex->getSourceRange()); bugreporter::trackNullOrUndefValue(N, ex, *R); Index: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp @@ -60,7 +60,8 @@ void LazyInitialize(std::unique_ptr &BT, const char *name) const { if (BT) return; - BT.reset(new BugType(this, name, categories::UnixAPI)); + BT.reset(new BugType(this, llvm::StringRef(name), + llvm::StringRef(categories::UnixAPI))); } void ReportOpenBug(CheckerContext &C, ProgramStateRef State, @@ -83,7 +84,7 @@ LazyInitialize(BT_open, "Improper use of 'open'"); - auto Report = llvm::make_unique(*BT_open, Msg, N); + auto Report = llvm::make_unique(*BT_open, StringRef(Msg), N); Report->addRange(SR); C.emitReport(std::move(Report)); } Index: clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp @@ -149,7 +149,7 @@ SmallString<80> Errmsg("Function '"); Errmsg += FuncInfo.Func.getFunctionName(); Errmsg += "' is called with an uninitialized va_list argument"; - reportUninitializedAccess(VAList, Errmsg.c_str(), C); + reportUninitializedAccess(VAList, llvm::StringRef(Errmsg.c_str()), C); break; } } Index: clang/lib/StaticAnalyzer/Checkers/VforkChecker.cpp =================================================================== --- clang/lib/StaticAnalyzer/Checkers/VforkChecker.cpp +++ clang/lib/StaticAnalyzer/Checkers/VforkChecker.cpp @@ -112,7 +112,7 @@ ASTContext &AC = C.getASTContext(); for (const char **id = ids; *id; ++id) - VforkWhitelist.insert(&AC.Idents.get(*id)); + VforkWhitelist.insert(&AC.Idents.get(llvm::StringRef(*id))); } return VforkWhitelist.count(II); Index: clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp =================================================================== --- clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp +++ clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp @@ -26,7 +26,8 @@ AnalyzerOptions::UserModeKind AnalyzerOptions::getUserMode() { if (UserMode == UMK_NotSet) { StringRef ModeStr = - Config.insert(std::make_pair("mode", "deep")).first->second; + Config.insert(std::make_pair("mode", "deep")) + .first->second; UserMode = llvm::StringSwitch(ModeStr) .Case("shallow", UMK_Shallow) .Case("deep", UMK_Deep) @@ -42,17 +43,18 @@ // Use the User Mode to set the default IPA value. // Note, we have to add the string to the Config map for the ConfigDumper // checker to function properly. - const char *DefaultIPA = nullptr; + StringRef DefaultIPA; UserModeKind HighLevelMode = getUserMode(); if (HighLevelMode == UMK_Shallow) DefaultIPA = "inlining"; else if (HighLevelMode == UMK_Deep) DefaultIPA = "dynamic-bifurcate"; - assert(DefaultIPA); + assert(!DefaultIPA.empty()); // Lookup the ipa configuration option, use the default from User Mode. StringRef ModeStr = - Config.insert(std::make_pair("ipa", DefaultIPA)).first->second; + Config.insert(std::make_pair(StringRef("ipa"), DefaultIPA)) + .first->second; IPAKind IPAConfig = llvm::StringSwitch(ModeStr) .Case("none", IPAK_None) .Case("basic-inlining", IPAK_BasicInlining) @@ -75,10 +77,11 @@ return false; if (!CXXMemberInliningMode) { - static const char *ModeKey = "c++-inlining"; + StringRef ModeKey = "c++-inlining"; StringRef ModeStr = - Config.insert(std::make_pair(ModeKey, "destructors")).first->second; + Config.insert(std::make_pair(ModeKey, StringRef("destructors"))) + .first->second; CXXInlineableMemberKind &MutableMode = const_cast(CXXMemberInliningMode); @@ -100,7 +103,9 @@ return CXXMemberInliningMode >= K; } -static StringRef toString(bool b) { return b ? "true" : "false"; } +static StringRef toString(bool b) { + return llvm::StringRef(b ? "true" : "false"); +} StringRef AnalyzerOptions::getCheckerOption(StringRef CheckerName, StringRef OptionName, Index: clang/lib/StaticAnalyzer/Core/BugReporter.cpp =================================================================== --- clang/lib/StaticAnalyzer/Core/BugReporter.cpp +++ clang/lib/StaticAnalyzer/Core/BugReporter.cpp @@ -1841,7 +1841,7 @@ if (str) { PathDiagnosticLocation L(TermCond ? TermCond : Term, SM, PDB.LC); PathDiagnosticEventPiece *PE = - new PathDiagnosticEventPiece(L, str); + new PathDiagnosticEventPiece(L, llvm::StringRef(str)); PE->setPrunable(true); addEdgeToPath(PD.getActivePath(), PrevLoc, PE->getLocation(), PDB.LC); Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp =================================================================== --- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp +++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp @@ -1368,7 +1368,8 @@ return nullptr; PathDiagnosticEventPiece *Event = new PathDiagnosticEventPiece( - Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage); + Loc, + llvm::StringRef(tookTrue ? GenericTrueMessage : GenericFalseMessage)); return Event; } @@ -1610,8 +1611,8 @@ bool ConditionBRVisitor::isPieceMessageGeneric( const PathDiagnosticPiece *Piece) { - return Piece->getString() == GenericTrueMessage || - Piece->getString() == GenericFalseMessage; + return Piece->getString() == llvm::StringRef(GenericTrueMessage) || + Piece->getString() == llvm::StringRef(GenericFalseMessage); } std::unique_ptr Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp =================================================================== --- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp +++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp @@ -378,7 +378,8 @@ // Process any special transfer function for dead symbols. // A tag to track convenience transitions, which can be removed at cleanup. - static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node"); + static SimpleProgramPointTag cleanupTag(llvm::StringRef(TagProviderName), + "Clean Node"); if (!SymReaper.hasDeadSymbols()) { // Generate a CleanedNode that has the environment and store cleaned // up. Since no symbols are dead, we can optimize and not clean out @@ -1433,7 +1434,8 @@ // FIXME: Refactor this into a checker. if (BlockCount >= AMgr.options.maxBlockVisitOnPath) { - static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded"); + static SimpleProgramPointTag tag(llvm::StringRef(TagProviderName), + "Block count exceeded"); const ExplodedNode *Sink = nodeBuilder.generateSink(Pred->getState(), Pred, &tag); @@ -2324,8 +2326,8 @@ QualType ValTy = TR->getValueType(); if (const ReferenceType *RT = ValTy->getAs()) { - static SimpleProgramPointTag - loadReferenceTag(TagProviderName, "Load Reference"); + static SimpleProgramPointTag loadReferenceTag( + llvm::StringRef(TagProviderName), "Load Reference"); ExplodedNodeSet Tmp; evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state, location, &loadReferenceTag, @@ -2408,7 +2410,8 @@ // instead "int *p" is noted as // "Variable 'p' initialized to a null pointer value" - static SimpleProgramPointTag tag(TagProviderName, "Location"); + static SimpleProgramPointTag tag(llvm::StringRef(TagProviderName), + "Location"); Bldr.generateNode(NodeEx, Pred, state, &tag); } ExplodedNodeSet Tmp; @@ -2419,11 +2422,10 @@ std::pair ExprEngine::geteagerlyAssumeBinOpBifurcationTags() { - static SimpleProgramPointTag - eagerlyAssumeBinOpBifurcationTrue(TagProviderName, - "Eagerly Assume True"), - eagerlyAssumeBinOpBifurcationFalse(TagProviderName, - "Eagerly Assume False"); + static SimpleProgramPointTag eagerlyAssumeBinOpBifurcationTrue( + llvm::StringRef(TagProviderName), "Eagerly Assume True"), + eagerlyAssumeBinOpBifurcationFalse(llvm::StringRef(TagProviderName), + "Eagerly Assume False"); return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue, &eagerlyAssumeBinOpBifurcationFalse); } Index: clang/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp =================================================================== --- clang/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp +++ clang/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp @@ -106,7 +106,8 @@ SmallVector checkerOpts; for (unsigned i = 0, e = opts.CheckersControlList.size(); i != e; ++i) { const std::pair &opt = opts.CheckersControlList[i]; - checkerOpts.push_back(CheckerOptInfo(opt.first.c_str(), opt.second)); + checkerOpts.push_back( + CheckerOptInfo(llvm::StringRef(opt.first.c_str()), opt.second)); } return checkerOpts; } Index: clang/lib/Tooling/CommonOptionsParser.cpp =================================================================== --- clang/lib/Tooling/CommonOptionsParser.cpp +++ clang/lib/Tooling/CommonOptionsParser.cpp @@ -117,7 +117,7 @@ cl::HideUnrelatedOptions(Category); Compilations.reset(FixedCompilationDatabase::loadFromCommandLine(argc, argv)); - cl::ParseCommandLineOptions(argc, argv, Overview); + cl::ParseCommandLineOptions(argc, argv, llvm::StringRef(Overview)); cl::PrintOptionValues(); SourcePathList = SourcePaths; Index: clang/lib/Tooling/CompilationDatabase.cpp =================================================================== --- clang/lib/Tooling/CompilationDatabase.cpp +++ clang/lib/Tooling/CompilationDatabase.cpp @@ -282,13 +282,16 @@ FixedCompilationDatabase *FixedCompilationDatabase::loadFromCommandLine( int &Argc, const char *const *Argv, Twine Directory) { - const char *const *DoubleDash = std::find(Argv, Argv + Argc, StringRef("--")); + const char *const *DoubleDash = + std::find_if(Argv, Argv + Argc, [](const char *Value) { + return StringRef(Value) == StringRef("--"); + }); if (DoubleDash == Argv + Argc) return nullptr; std::vector CommandLine; CommandLine.reserve(Argv + Argc - DoubleDash - 1); for (auto Arg : ArrayRef(DoubleDash + 1, Argv + Argc)) - CommandLine.push_back(Arg); + CommandLine.push_back(llvm::StringRef(Arg)); Argc = DoubleDash - Argv; Index: clang/lib/Tooling/Core/Replacement.cpp =================================================================== --- clang/lib/Tooling/Core/Replacement.cpp +++ clang/lib/Tooling/Core/Replacement.cpp @@ -105,7 +105,7 @@ const std::pair DecomposedLocation = Sources.getDecomposedLoc(Start); const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first); - this->FilePath = Entry ? Entry->getName() : InvalidLocation; + this->FilePath = Entry ? Entry->getName() : llvm::StringRef(InvalidLocation); this->ReplacementRange = Range(DecomposedLocation.second, Length); this->ReplacementText = ReplacementText; } @@ -569,7 +569,7 @@ const std::map &FileToReplaces) { std::map Result; for (const auto &Entry : FileToReplaces) { - llvm::SmallString<256> CleanPath(Entry.first.data()); + llvm::SmallString<256> CleanPath(Entry.first); llvm::sys::path::remove_dots(CleanPath, /*remove_dot_dot=*/true); Result[CleanPath.str()] = std::move(Entry.second); } Index: clang/lib/Tooling/Tooling.cpp =================================================================== --- clang/lib/Tooling/Tooling.cpp +++ clang/lib/Tooling/Tooling.cpp @@ -361,8 +361,8 @@ return; // If there's no override in place add our resource dir. - Args.push_back("-resource-dir=" + - CompilerInvocation::GetResourcesPath(Argv0, MainAddr)); + Args.push_back("-resource-dir=" + CompilerInvocation::GetResourcesPath( + llvm::StringRef(Argv0), MainAddr)); } int ClangTool::run(ToolAction *Action) { Index: clang/tools/arcmt-test/arcmt-test.cpp =================================================================== --- clang/tools/arcmt-test/arcmt-test.cpp +++ clang/tools/arcmt-test/arcmt-test.cpp @@ -311,7 +311,7 @@ SourceManager &SM = Ctx.getSourceManager(); PresumedLoc PL = SM.getPresumedLoc(loc); - OS << llvm::sys::path::filename(PL.getFilename()); + OS << llvm::sys::path::filename(llvm::StringRef(PL.getFilename())); OS << ":" << PL.getLine() << ":" << PL.getColumn(); } @@ -323,7 +323,7 @@ PresumedLoc PL = SM.getPresumedLoc(range.getBegin()); - OS << llvm::sys::path::filename(PL.getFilename()); + OS << llvm::sys::path::filename(llvm::StringRef(PL.getFilename())); OS << " [" << PL.getLine() << ":" << PL.getColumn(); OS << " - "; @@ -343,10 +343,10 @@ int main(int argc, const char **argv) { void *MainAddr = (void*) (intptr_t) GetExecutablePath; - llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); + llvm::sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0])); - std::string - resourcesPath = CompilerInvocation::GetResourcesPath(argv[0], MainAddr); + std::string resourcesPath = + CompilerInvocation::GetResourcesPath(llvm::StringRef(argv[0]), MainAddr); int optargc = 0; for (; optargc != argc; ++optargc) { Index: clang/tools/c-index-test/core_main.cpp =================================================================== --- clang/tools/c-index-test/core_main.cpp +++ clang/tools/c-index-test/core_main.cpp @@ -195,15 +195,18 @@ //===----------------------------------------------------------------------===// int indextest_core_main(int argc, const char **argv) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); - assert(argv[1] == StringRef("core")); + assert(StringRef(argv[1]) == StringRef("core")); ++argv; --argc; std::vector CompArgs; - const char **DoubleDash = std::find(argv, argv + argc, StringRef("--")); + const char **DoubleDash = + std::find_if(argv, argv + argc, [](const char *Value) { + return StringRef(Value) == StringRef("--"); + }); if (DoubleDash != argv + argc) { CompArgs = std::vector(DoubleDash + 1, argv + argc); argc = DoubleDash - argv; Index: clang/tools/clang-check/ClangCheck.cpp =================================================================== --- clang/tools/clang-check/ClangCheck.cpp +++ clang/tools/clang-check/ClangCheck.cpp @@ -36,7 +36,7 @@ using namespace clang::tooling; using namespace llvm; -static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); +static cl::extrahelp CommonHelp((StringRef(CommonOptionsParser::HelpMessage))); static cl::extrahelp MoreHelp( "\tFor example, to run clang-check on all files in a subtree of the\n" "\tsource tree, use:\n" @@ -55,30 +55,36 @@ static cl::OptionCategory ClangCheckCategory("clang-check options"); static std::unique_ptr Options(createDriverOptTable()); static cl::opt -ASTDump("ast-dump", cl::desc(Options->getOptionHelpText(options::OPT_ast_dump)), - cl::cat(ClangCheckCategory)); + ASTDump("ast-dump", cl::desc(llvm::StringRef( + Options->getOptionHelpText(options::OPT_ast_dump))), + cl::cat(ClangCheckCategory)); static cl::opt -ASTList("ast-list", cl::desc(Options->getOptionHelpText(options::OPT_ast_list)), - cl::cat(ClangCheckCategory)); + ASTList("ast-list", cl::desc(llvm::StringRef( + Options->getOptionHelpText(options::OPT_ast_list))), + cl::cat(ClangCheckCategory)); static cl::opt -ASTPrint("ast-print", - cl::desc(Options->getOptionHelpText(options::OPT_ast_print)), - cl::cat(ClangCheckCategory)); -static cl::opt ASTDumpFilter( - "ast-dump-filter", - cl::desc(Options->getOptionHelpText(options::OPT_ast_dump_filter)), + ASTPrint("ast-print", cl::desc(llvm::StringRef(Options->getOptionHelpText( + options::OPT_ast_print))), + cl::cat(ClangCheckCategory)); +static cl::opt + ASTDumpFilter("ast-dump-filter", + cl::desc(llvm::StringRef(Options->getOptionHelpText( + options::OPT_ast_dump_filter))), + cl::cat(ClangCheckCategory)); +static cl::opt Analyze( + "analyze", + cl::desc(llvm::StringRef(Options->getOptionHelpText(options::OPT_analyze))), cl::cat(ClangCheckCategory)); -static cl::opt -Analyze("analyze", cl::desc(Options->getOptionHelpText(options::OPT_analyze)), - cl::cat(ClangCheckCategory)); -static cl::opt -Fixit("fixit", cl::desc(Options->getOptionHelpText(options::OPT_fixit)), - cl::cat(ClangCheckCategory)); -static cl::opt FixWhatYouCan( - "fix-what-you-can", - cl::desc(Options->getOptionHelpText(options::OPT_fix_what_you_can)), +static cl::opt Fixit( + "fixit", + cl::desc(llvm::StringRef(Options->getOptionHelpText(options::OPT_fixit))), cl::cat(ClangCheckCategory)); +static cl::opt + FixWhatYouCan("fix-what-you-can", + cl::desc(llvm::StringRef(Options->getOptionHelpText( + options::OPT_fix_what_you_can))), + cl::cat(ClangCheckCategory)); namespace { @@ -150,7 +156,7 @@ } // namespace int main(int argc, const char **argv) { - llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); + llvm::sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0])); // Initialize targets for clang module support. llvm::InitializeAllTargets(); Index: clang/tools/clang-format/ClangFormat.cpp =================================================================== --- clang/tools/clang-format/ClangFormat.cpp +++ clang/tools/clang-format/ClangFormat.cpp @@ -60,7 +60,7 @@ cl::cat(ClangFormatCategory)); static cl::opt Style("style", - cl::desc(clang::format::StyleOptionHelpDescription), + cl::desc(llvm::StringRef(clang::format::StyleOptionHelpDescription)), cl::init("file"), cl::cat(ClangFormatCategory)); static cl::opt FallbackStyle("fallback-style", @@ -315,7 +315,7 @@ } int main(int argc, const char **argv) { - llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); + llvm::sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0])); cl::HideUnrelatedOptions(ClangFormatCategory); Index: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp =================================================================== --- clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp +++ clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp @@ -918,7 +918,7 @@ } int main(int argc, const char **argv) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0])); cl::HideUnrelatedOptions(ClangOffloadBundlerCategory); cl::SetVersionPrinter(PrintVersion); Index: clang/tools/diagtool/TreeView.cpp =================================================================== --- clang/tools/diagtool/TreeView.cpp +++ clang/tools/diagtool/TreeView.cpp @@ -162,7 +162,7 @@ ShowAll = true; break; case 1: - RootGroup = argv[0]; + RootGroup = llvm::StringRef(argv[0]); if (RootGroup.startswith("-W")) RootGroup = RootGroup.substr(2); if (RootGroup == "everything") Index: clang/tools/diagtool/diagtool_main.cpp =================================================================== --- clang/tools/diagtool/diagtool_main.cpp +++ clang/tools/diagtool/diagtool_main.cpp @@ -17,7 +17,7 @@ int main(int argc, char *argv[]) { if (argc > 1) - if (DiagTool *tool = diagTools->getTool(argv[1])) + if (DiagTool *tool = diagTools->getTool(llvm::StringRef(argv[1]))) return tool->run(argc - 2, &argv[2], llvm::outs()); llvm::errs() << "usage: diagtool []\n\n"; Index: clang/tools/driver/driver.cpp =================================================================== --- clang/tools/driver/driver.cpp +++ clang/tools/driver/driver.cpp @@ -103,12 +103,12 @@ const char *Str = GetStableCStr(SavedStrings, Edit.substr(1)); OS << "### Adding argument " << Str << " at beginning\n"; - Args.insert(Args.begin() + 1, Str); + Args.insert(Args.begin() + 1, llvm::StringRef(Str)); } else if (Edit[0] == '+') { const char *Str = GetStableCStr(SavedStrings, Edit.substr(1)); OS << "### Adding argument " << Str << " at end\n"; - Args.push_back(Str); + Args.push_back(llvm::StringRef(Str)); } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") && Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) { StringRef MatchPattern = Edit.substr(2).split('/').first; @@ -123,7 +123,7 @@ if (Repl != Args[i]) { OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n"; - Args[i] = GetStableCStr(SavedStrings, Repl); + Args[i] = llvm::StringRef(GetStableCStr(SavedStrings, Repl)); } } } else if (Edit[0] == 'x' || Edit[0] == 'X') { @@ -158,7 +158,8 @@ ++i; } OS << "### Adding argument " << Edit << " at end\n"; - Args.push_back(GetStableCStr(SavedStrings, '-' + Edit.str())); + Args.push_back( + llvm::StringRef(GetStableCStr(SavedStrings, '-' + Edit.str()))); } else { OS << "### Unrecognized edit: " << Edit << "\n"; } @@ -205,14 +206,15 @@ auto it = ArgVector.begin(); if (it != ArgVector.end()) ++it; - ArgVector.insert(it, GetStableCStr(SavedStrings, Mode)); + ArgVector.insert(it, StringRef(GetStableCStr(SavedStrings, Mode))); } if (!Target.empty()) { auto it = ArgVector.begin(); if (it != ArgVector.end()) ++it; - const char *arr[] = {"-target", GetStableCStr(SavedStrings, Target)}; + StringRef arr[] = {"-target", + StringRef(GetStableCStr(SavedStrings, Target))}; ArgVector.insert(it, std::begin(arr), std::end(arr)); } } @@ -305,7 +307,7 @@ } int main(int argc_, const char **argv_) { - llvm::sys::PrintStackTraceOnErrorSignal(argv_[0]); + llvm::sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv_[0])); llvm::PrettyStackTraceProgram X(argc_, argv_); llvm::llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. Index: clang/tools/libclang/ARCMigrate.cpp =================================================================== --- clang/tools/libclang/ARCMigrate.cpp +++ clang/tools/libclang/ARCMigrate.cpp @@ -59,7 +59,8 @@ TextDiagnosticBuffer diagBuffer; std::unique_ptr remap(new Remap()); - bool err = arcmt::getFileRemappings(remap->Vec, migrate_dir_path,&diagBuffer); + bool err = arcmt::getFileRemappings( + remap->Vec, llvm::StringRef(migrate_dir_path), &diagBuffer); if (err) { if (Logging) { Index: clang/tools/libclang/BuildSystem.cpp =================================================================== --- clang/tools/libclang/BuildSystem.cpp +++ clang/tools/libclang/BuildSystem.cpp @@ -45,15 +45,16 @@ if (!path::is_absolute(realPath)) return CXError_InvalidArguments; - for (path::const_iterator - PI = path::begin(virtualPath), - PE = path::end(virtualPath); PI != PE; ++PI) { + for (path::const_iterator PI = path::begin(llvm::StringRef(virtualPath)), + PE = path::end(llvm::StringRef(virtualPath)); + PI != PE; ++PI) { StringRef Comp = *PI; if (Comp == "." || Comp == "..") return CXError_InvalidArguments; } - unwrap(VFO)->addFileMapping(virtualPath, realPath); + unwrap(VFO)->addFileMapping(llvm::StringRef(virtualPath), + llvm::StringRef(realPath)); return CXError_Success; } Index: clang/tools/libclang/CIndex.cpp =================================================================== --- clang/tools/libclang/CIndex.cpp +++ clang/tools/libclang/CIndex.cpp @@ -3730,7 +3730,7 @@ if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) setThreadBackgroundPriority(); - bool hadError = cxtu::getASTUnit(TU)->Save(FileName); + bool hadError = cxtu::getASTUnit(TU)->Save(llvm::StringRef(FileName)); return hadError ? CXSaveError_Unknown : CXSaveError_None; } @@ -3935,7 +3935,7 @@ ASTUnit *CXXUnit = cxtu::getASTUnit(TU); FileManager &FMgr = CXXUnit->getFileManager(); - return const_cast(FMgr.getFile(file_name)); + return const_cast(FMgr.getFile(llvm::StringRef(file_name))); } unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, @@ -7357,7 +7357,7 @@ const RawComment *RC = Context.getRawCommentForAnyRedecl(D); if (RC) { - StringRef BriefText = RC->getBriefText(Context); + StringRef BriefText = llvm::StringRef(RC->getBriefText(Context)); // Don't duplicate the string because RawComment ensures that this memory // will not go away. Index: clang/tools/libclang/CIndexCodeCompletion.cpp =================================================================== --- clang/tools/libclang/CIndexCodeCompletion.cpp +++ clang/tools/libclang/CIndexCodeCompletion.cpp @@ -701,13 +701,13 @@ CaptureCompletionResults Capture(Opts, *Results, &TU); // Perform completion. - AST->CodeComplete(complete_filename, complete_line, complete_column, - RemappedFiles, (options & CXCodeComplete_IncludeMacros), - (options & CXCodeComplete_IncludeCodePatterns), - IncludeBriefComments, Capture, - CXXIdx->getPCHContainerOperations(), *Results->Diag, - Results->LangOpts, *Results->SourceMgr, *Results->FileMgr, - Results->Diagnostics, Results->TemporaryBuffers); + AST->CodeComplete( + llvm::StringRef(complete_filename), complete_line, complete_column, + RemappedFiles, (options & CXCodeComplete_IncludeMacros), + (options & CXCodeComplete_IncludeCodePatterns), IncludeBriefComments, + Capture, CXXIdx->getPCHContainerOperations(), *Results->Diag, + Results->LangOpts, *Results->SourceMgr, *Results->FileMgr, + Results->Diagnostics, Results->TemporaryBuffers); Results->DiagnosticsWrappers.resize(Results->Diagnostics.size()); @@ -955,7 +955,7 @@ for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end(); C != CEnd; ++C) { if (C->Kind == CodeCompletionString::CK_TypedText) - AppendToString(Result, C->Text, Buffer); + AppendToString(Result, llvm::StringRef(C->Text), Buffer); } return Result; Index: clang/tools/libclang/CIndexUSRs.cpp =================================================================== --- clang/tools/libclang/CIndexUSRs.cpp +++ clang/tools/libclang/CIndexUSRs.cpp @@ -95,8 +95,8 @@ CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); - OS << extractUSRSuffix(clang_getCString(classUSR)); - generateUSRForObjCIvar(name, OS); + OS << extractUSRSuffix(llvm::StringRef(clang_getCString(classUSR))); + generateUSRForObjCIvar(llvm::StringRef(name), OS); return cxstring::createDup(OS.str()); } @@ -105,22 +105,22 @@ CXString classUSR) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); - OS << extractUSRSuffix(clang_getCString(classUSR)); - generateUSRForObjCMethod(name, isInstanceMethod, OS); + OS << extractUSRSuffix(llvm::StringRef(clang_getCString(classUSR))); + generateUSRForObjCMethod(llvm::StringRef(name), isInstanceMethod, OS); return cxstring::createDup(OS.str()); } CXString clang_constructUSR_ObjCClass(const char *name) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); - generateUSRForObjCClass(name, OS); + generateUSRForObjCClass(llvm::StringRef(name), OS); return cxstring::createDup(OS.str()); } CXString clang_constructUSR_ObjCProtocol(const char *name) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); - generateUSRForObjCProtocol(name, OS); + generateUSRForObjCProtocol(llvm::StringRef(name), OS); return cxstring::createDup(OS.str()); } @@ -128,7 +128,8 @@ const char *category_name) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); - generateUSRForObjCCategory(class_name, category_name, OS); + generateUSRForObjCCategory(llvm::StringRef(class_name), + llvm::StringRef(category_name), OS); return cxstring::createDup(OS.str()); } @@ -136,8 +137,9 @@ CXString classUSR) { SmallString<128> Buf(getUSRSpacePrefix()); llvm::raw_svector_ostream OS(Buf); - OS << extractUSRSuffix(clang_getCString(classUSR)); - generateUSRForObjCProperty(property, /*isClassProp=*/false, OS); + OS << extractUSRSuffix(llvm::StringRef(clang_getCString(classUSR))); + generateUSRForObjCProperty(llvm::StringRef(property), /*isClassProp=*/false, + OS); return cxstring::createDup(OS.str()); } Index: clang/tools/libclang/CIndexer.cpp =================================================================== --- clang/tools/libclang/CIndexer.cpp +++ clang/tools/libclang/CIndexer.cpp @@ -67,7 +67,7 @@ llvm_unreachable("Call to dladdr() failed"); // We now have the CIndex directory, locate clang relative to it. - LibClangPath += llvm::sys::path::parent_path(info.dli_fname); + LibClangPath += llvm::sys::path::parent_path(llvm::StringRef(info.dli_fname)); #endif llvm::sys::path::append(LibClangPath, "clang", CLANG_VERSION_STRING); Index: clang/tools/libclang/CXCompilationDatabase.cpp =================================================================== --- clang/tools/libclang/CXCompilationDatabase.cpp +++ clang/tools/libclang/CXCompilationDatabase.cpp @@ -17,7 +17,8 @@ CXCompilationDatabase_Error Err = CXCompilationDatabase_NoError; std::unique_ptr db = - CompilationDatabase::loadFromDirectory(BuildDir, ErrorMsg); + CompilationDatabase::loadFromDirectory(llvm::StringRef(BuildDir), + ErrorMsg); if (!db) { fprintf(stderr, "LIBCLANG TOOLING ERROR: %s\n", ErrorMsg.c_str()); @@ -49,7 +50,8 @@ const char *CompleteFileName) { if (CompilationDatabase *db = static_cast(CDb)) { - std::vector CCmd(db->getCompileCommands(CompleteFileName)); + std::vector CCmd( + db->getCompileCommands(llvm::StringRef(CompleteFileName))); if (!CCmd.empty()) return new AllocatedCXCompileCommands(std::move(CCmd)); } Index: clang/tools/libclang/CXLoadedDiagnostic.cpp =================================================================== --- clang/tools/libclang/CXLoadedDiagnostic.cpp +++ clang/tools/libclang/CXLoadedDiagnostic.cpp @@ -250,7 +250,7 @@ CXDiagnosticSet DiagLoader::load(const char *file) { TopDiags = llvm::make_unique(); - std::error_code EC = readDiagnostics(file); + std::error_code EC = readDiagnostics(llvm::StringRef(file)); if (EC) { switch (EC.value()) { case static_cast(serialized_diags::SDError::HandlerFailed): @@ -381,8 +381,9 @@ if (std::error_code EC = readLocation(Location, D.DiagLoc)) return EC; D.category = Category; - D.DiagOption = Flag ? TopDiags->WarningFlags[Flag] : ""; - D.CategoryText = Category ? TopDiags->Categories[Category] : ""; + D.DiagOption = llvm::StringRef(Flag ? TopDiags->WarningFlags[Flag] : ""); + D.CategoryText = + llvm::StringRef(Category ? TopDiags->Categories[Category] : ""); D.Spelling = TopDiags->copyString(Message); return std::error_code(); } Index: clang/tools/libclang/CXType.cpp =================================================================== --- clang/tools/libclang/CXType.cpp +++ clang/tools/libclang/CXType.cpp @@ -825,7 +825,7 @@ return CXTypeLayoutError_InvalidFieldName; // lookup field ASTContext &Ctx = cxtu::getASTUnit(GetTU(PT))->getASTContext(); - IdentifierInfo *II = &Ctx.Idents.get(S); + IdentifierInfo *II = &Ctx.Idents.get(llvm::StringRef(S)); DeclarationName FieldName(II); const RecordDecl *RD = dyn_cast_or_null(cxcursor::getCursorDecl(PC)); Index: clang/tools/libclang/Indexing.cpp =================================================================== --- clang/tools/libclang/Indexing.cpp +++ clang/tools/libclang/Indexing.cpp @@ -501,7 +501,8 @@ for (auto &UF : unsaved_files) { std::unique_ptr MB = llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); - CInvok->getPreprocessorOpts().addRemappedFile(UF.Filename, MB.get()); + CInvok->getPreprocessorOpts().addRemappedFile(llvm::StringRef(UF.Filename), + MB.get()); BufOwner->push_back(std::move(MB)); } Index: clang/unittests/AST/ASTImporterTest.cpp =================================================================== --- clang/unittests/AST/ASTImporterTest.cpp +++ clang/unittests/AST/ASTImporterTest.cpp @@ -71,8 +71,8 @@ ToCtx.getSourceManager().getFileManager().getVirtualFileSystem().get()); vfs::InMemoryFileSystem *MFS = static_cast( OFS->overlays_begin()->get()); - MFS->addFile(InputFileName, 0, - llvm::MemoryBuffer::getMemBuffer(FromCode.c_str())); + MFS->addFile(InputFileName, 0, llvm::MemoryBuffer::getMemBuffer( + llvm::StringRef(FromCode.c_str()))); ASTImporter Importer(ToCtx, ToAST->getFileManager(), FromCtx, FromAST->getFileManager(), false); Index: clang/unittests/AST/CommentLexer.cpp =================================================================== --- clang/unittests/AST/CommentLexer.cpp +++ clang/unittests/AST/CommentLexer.cpp @@ -46,21 +46,24 @@ void lexString(const char *Source, std::vector &Toks); StringRef getCommandName(const Token &Tok) { - return Traits.getCommandInfo(Tok.getCommandID())->Name; + return llvm::StringRef(Traits.getCommandInfo(Tok.getCommandID())->Name); } StringRef getVerbatimBlockName(const Token &Tok) { - return Traits.getCommandInfo(Tok.getVerbatimBlockID())->Name; + return llvm::StringRef( + Traits.getCommandInfo(Tok.getVerbatimBlockID())->Name); } StringRef getVerbatimLineName(const Token &Tok) { - return Traits.getCommandInfo(Tok.getVerbatimLineID())->Name; + return llvm::StringRef( + Traits.getCommandInfo(Tok.getVerbatimLineID())->Name); } }; void CommentLexerTest::lexString(const char *Source, std::vector &Toks) { - std::unique_ptr Buf = MemoryBuffer::getMemBuffer(Source); + std::unique_ptr Buf = + MemoryBuffer::getMemBuffer(llvm::StringRef(Source)); FileID File = SourceMgr.createFileID(std::move(Buf)); SourceLocation Begin = SourceMgr.getLocForStartOfFile(File); Index: clang/unittests/AST/CommentParser.cpp =================================================================== --- clang/unittests/AST/CommentParser.cpp +++ clang/unittests/AST/CommentParser.cpp @@ -53,7 +53,8 @@ }; FullComment *CommentParserTest::parseString(const char *Source) { - std::unique_ptr Buf = MemoryBuffer::getMemBuffer(Source); + std::unique_ptr Buf = + MemoryBuffer::getMemBuffer(llvm::StringRef(Source)); FileID File = SourceMgr.createFileID(std::move(Buf)); SourceLocation Begin = SourceMgr.getLocForStartOfFile(File); Index: clang/unittests/AST/DeclPrinterTest.cpp =================================================================== --- clang/unittests/AST/DeclPrinterTest.cpp +++ clang/unittests/AST/DeclPrinterTest.cpp @@ -679,12 +679,12 @@ for (unsigned i = 0, e = llvm::array_lengthof(OperatorNames); i != e; ++i) { SmallString<128> Code; Code.append("struct Z { void operator"); - Code.append(OperatorNames[i]); + Code.append(llvm::StringRef(OperatorNames[i])); Code.append("(Z z); };"); SmallString<128> Expected; Expected.append("void operator"); - Expected.append(OperatorNames[i]); + Expected.append(llvm::StringRef(OperatorNames[i])); Expected.append("(Z z)"); // Should be: with semicolon @@ -703,12 +703,12 @@ for (unsigned i = 0, e = llvm::array_lengthof(OperatorNames); i != e; ++i) { SmallString<128> Code; Code.append("struct Z { void operator"); - Code.append(OperatorNames[i]); + Code.append(llvm::StringRef(OperatorNames[i])); Code.append("(); };"); SmallString<128> Expected; Expected.append("void operator"); - Expected.append(OperatorNames[i]); + Expected.append(llvm::StringRef(OperatorNames[i])); Expected.append("()"); // Should be: with semicolon Index: clang/unittests/Basic/FileManagerTest.cpp =================================================================== --- clang/unittests/Basic/FileManagerTest.cpp +++ clang/unittests/Basic/FileManagerTest.cpp @@ -37,7 +37,7 @@ Data.IsDirectory = !IsFile; Data.IsNamedPipe = false; Data.InPCH = false; - StatCalls[Path] = Data; + StatCalls[llvm::StringRef(Path)] = Data; } public: Index: clang/unittests/Basic/SourceManagerTest.cpp =================================================================== --- clang/unittests/Basic/SourceManagerTest.cpp +++ clang/unittests/Basic/SourceManagerTest.cpp @@ -73,7 +73,7 @@ "#define M(x) [x]\n" "M(foo)"; std::unique_ptr Buf = - llvm::MemoryBuffer::getMemBuffer(source); + llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(source)); FileID mainFileID = SourceMgr.createFileID(std::move(Buf)); SourceMgr.setMainFileID(mainFileID); @@ -127,7 +127,7 @@ "int y;"; std::unique_ptr Buf = - llvm::MemoryBuffer::getMemBuffer(Source); + llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(Source)); FileID MainFileID = SourceMgr.createFileID(std::move(Buf)); SourceMgr.setMainFileID(MainFileID); @@ -187,9 +187,9 @@ "CONCAT(1,1)\n"; std::unique_ptr HeaderBuf = - llvm::MemoryBuffer::getMemBuffer(header); + llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(header)); std::unique_ptr MainBuf = - llvm::MemoryBuffer::getMemBuffer(main); + llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(main)); FileID mainFileID = SourceMgr.createFileID(std::move(MainBuf)); SourceMgr.setMainFileID(mainFileID); @@ -288,9 +288,9 @@ "#include M(INC2)\n"; std::unique_ptr HeaderBuf = - llvm::MemoryBuffer::getMemBuffer(header); + llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(header)); std::unique_ptr MainBuf = - llvm::MemoryBuffer::getMemBuffer(main); + llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(main)); SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(MainBuf))); const FileEntry *headerFile = FileMgr.getVirtualFile("/test-header.h", Index: clang/unittests/Lex/PPCallbacksTest.cpp =================================================================== --- clang/unittests/Lex/PPCallbacksTest.cpp +++ clang/unittests/Lex/PPCallbacksTest.cpp @@ -138,7 +138,8 @@ llvm::MemoryBuffer::getMemBuffer("\n")); // Add header's parent path to search path. - StringRef SearchPath = llvm::sys::path::parent_path(HeaderPath); + StringRef SearchPath = + llvm::sys::path::parent_path(llvm::StringRef(HeaderPath)); const DirectoryEntry *DE = FileMgr.getDirectory(SearchPath); DirectoryLookup DL(DE, SrcMgr::C_User, false); HeaderInfo.AddSearchPath(DL, IsSystemHeader); @@ -157,7 +158,7 @@ CharSourceRange InclusionDirectiveFilenameRange(const char* SourceText, const char* HeaderPath, bool SystemHeader) { std::unique_ptr Buf = - llvm::MemoryBuffer::getMemBuffer(SourceText); + llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(SourceText)); SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf))); VoidModuleLoader ModLoader; @@ -195,7 +196,8 @@ OpenCLLangOpts.OpenCL = 1; std::unique_ptr SourceBuf = - llvm::MemoryBuffer::getMemBuffer(SourceText, "test.cl"); + llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(SourceText), + "test.cl"); SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(SourceBuf))); VoidModuleLoader ModLoader; Index: clang/unittests/Lex/PPConditionalDirectiveRecordTest.cpp =================================================================== --- clang/unittests/Lex/PPConditionalDirectiveRecordTest.cpp +++ clang/unittests/Lex/PPConditionalDirectiveRecordTest.cpp @@ -89,7 +89,7 @@ "9\n"; std::unique_ptr Buf = - llvm::MemoryBuffer::getMemBuffer(source); + llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(source)); SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf))); VoidModuleLoader ModLoader; Index: clang/unittests/Tooling/CommentHandlerTest.cpp =================================================================== --- clang/unittests/Tooling/CommentHandlerTest.cpp +++ clang/unittests/Tooling/CommentHandlerTest.cpp @@ -205,7 +205,7 @@ "#endif */"; CommentHandlerVisitor Visitor; - EXPECT_TRUE(Visitor.runOver(Source)); + EXPECT_TRUE(Visitor.runOver(llvm::StringRef(Source))); CommentVerifier Verifier = Visitor.GetVerifier(); Verifier.Match(Source, 1, 1); } Index: clang/unittests/Tooling/RecursiveASTVisitorTestCallVisitor.cpp =================================================================== --- clang/unittests/Tooling/RecursiveASTVisitorTestCallVisitor.cpp +++ clang/unittests/Tooling/RecursiveASTVisitorTestCallVisitor.cpp @@ -101,7 +101,8 @@ // Use Traverse, not Visit, to check that data recursion optimization isn't // bypassing the call of this function. bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *CE) { - Match(getOperatorSpelling(CE->getOperator()), CE->getExprLoc()); + Match(llvm::StringRef(getOperatorSpelling(CE->getOperator())), + CE->getExprLoc()); return ExpectedLocationVisitor:: TraverseCXXOperatorCallExpr(CE); } Index: clang/utils/TableGen/ClangAttrEmitter.cpp =================================================================== --- clang/utils/TableGen/ClangAttrEmitter.cpp +++ clang/utils/TableGen/ClangAttrEmitter.cpp @@ -1938,7 +1938,7 @@ void emitDefaultDefines(raw_ostream &OS) const { // Default the macro unless this is a root class (i.e. Attr). if (SuperClass) { - emitDefaultDefine(OS, Descriptor.MacroName, + emitDefaultDefine(OS, StringRef(Descriptor.MacroName), SuperClass->Descriptor.MacroName); } } @@ -1952,7 +1952,7 @@ SubClass->emitAttrList(OS); } - ::emitAttrList(OS, Descriptor.MacroName, Attrs); + ::emitAttrList(OS, StringRef(Descriptor.MacroName), Attrs); } void classifyAttrOnRoot(Record *Attr) { Index: clang/utils/TableGen/TableGen.cpp =================================================================== --- clang/utils/TableGen/TableGen.cpp +++ clang/utils/TableGen/TableGen.cpp @@ -245,7 +245,7 @@ } int main(int argc, char **argv) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); Index: lld/COFF/Driver.cpp =================================================================== --- lld/COFF/Driver.cpp +++ lld/COFF/Driver.cpp @@ -229,9 +229,9 @@ {"wWinMain", "wWinMainCRTStartup"}, }; for (auto E : Entries) { - StringRef Entry = Symtab.findMangle(mangle(E[0])); + StringRef Entry = Symtab.findMangle(mangle(llvm::StringRef(E[0]))); if (!Entry.empty() && !isa(Symtab.find(Entry)->Body)) - return mangle(E[1]); + return mangle(llvm::StringRef(E[1])); } return ""; } @@ -611,8 +611,9 @@ if (auto *Arg = Args.getLastArg(OPT_entry)) { Config->Entry = addUndefined(mangle(Arg->getValue())); } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) { - StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12" - : "_DllMainCRTStartup"; + StringRef S = + llvm::StringRef((Config->Machine == I386) ? "__DllMainCRTStartup@12" + : "_DllMainCRTStartup"); Config->Entry = addUndefined(S); } else if (!Config->NoEntry) { // Windows specific -- If entry point name is not given, we need to Index: lld/COFF/DriverUtils.cpp =================================================================== --- lld/COFF/DriverUtils.cpp +++ lld/COFF/DriverUtils.cpp @@ -55,7 +55,7 @@ const char *Exe = Saver.save(*ExeOrErr).data(); Args.insert(Args.begin(), Exe); Args.push_back(nullptr); - if (llvm::sys::ExecuteAndWait(Args[0], Args.data()) != 0) { + if (llvm::sys::ExecuteAndWait(llvm::StringRef(Args[0]), Args.data()) != 0) { for (const char *S : Args) if (S) llvm::errs() << S << " "; Index: lld/ELF/Driver.cpp =================================================================== --- lld/ELF/Driver.cpp +++ lld/ELF/Driver.cpp @@ -686,7 +686,8 @@ Config->EMachine != EM_AMDGPU) { // -e was not specified. Use the default start symbol name // if it is resolvable. - Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start"; + Config->Entry = + llvm::StringRef((Config->EMachine == EM_MIPS) ? "__start" : "_start"); } if (!HasEntryAddr && !Config->Entry.empty()) { if (Symtab.find(Config->Entry)) Index: lld/ELF/Mips.cpp =================================================================== --- lld/ELF/Mips.cpp +++ lld/ELF/Mips.cpp @@ -59,7 +59,7 @@ } static StringRef getNanName(bool IsNan2008) { - return IsNan2008 ? "2008" : "legacy"; + return llvm::StringRef(IsNan2008 ? "2008" : "legacy"); } static StringRef getFpName(bool IsFp64) { return IsFp64 ? "64" : "32"; } Index: lld/ELF/OutputSections.cpp =================================================================== --- lld/ELF/OutputSections.cpp +++ lld/ELF/OutputSections.cpp @@ -1617,8 +1617,8 @@ // prepare to create one by allocating a version identifier and creating a // dynstr entry for the version name. if (NV.Index == 0) { - NV.StrTab = Out::DynStrTab->addString( - SS->file()->getStringTable().data() + SS->Verdef->getAux()->vda_name); + NV.StrTab = Out::DynStrTab->addString(llvm::StringRef( + SS->file()->getStringTable().data() + SS->Verdef->getAux()->vda_name)); NV.Index = NextIndex++; } SS->symbol()->VersionId = NV.Index; Index: lld/ELF/Relocations.cpp =================================================================== --- lld/ELF/Relocations.cpp +++ lld/ELF/Relocations.cpp @@ -415,7 +415,7 @@ static StringRef getSymbolName(const elf::ObjectFile &File, SymbolBody &Body) { if (Body.isLocal() && Body.getNameOffset()) - return File.getStringTable().data() + Body.getNameOffset(); + return llvm::StringRef(File.getStringTable().data() + Body.getNameOffset()); if (!Body.isLocal()) return Body.getName(); return ""; Index: lld/ELF/Writer.cpp =================================================================== --- lld/ELF/Writer.cpp +++ lld/ELF/Writer.cpp @@ -95,10 +95,12 @@ if (Config->Relocatable) return Name; - for (StringRef V : - {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.", - ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.", - ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) { + static const StringRef Names[]{ + ".text.", ".rodata.", ".data.rel.ro.", ".data.", + ".bss.", ".init_array.", ".fini_array.", ".ctors.", + ".dtors.", ".tbss.", ".gcc_except_table.", ".tdata.", + ".ARM.exidx."}; + for (StringRef V : Names) { StringRef Prefix = V.drop_back(); if (Name.startswith(V) || Name == Prefix) return Prefix; @@ -135,8 +137,9 @@ EhOutputSection EhFrame; GotSection Got; PltSection Plt; - RelocationSection RelaDyn(Config->Rela ? ".rela.dyn" : ".rel.dyn", - Config->ZCombreloc); + RelocationSection RelaDyn( + llvm::StringRef(Config->Rela ? ".rela.dyn" : ".rel.dyn"), + Config->ZCombreloc); StringTableSection ShStrTab(".shstrtab", false); VersionTableSection VerSym; VersionNeedSection VerNeed; @@ -187,7 +190,7 @@ GnuHashTab.reset(new GnuHashTableSection); if (Config->SysvHash) HashTab.reset(new HashTableSection); - StringRef S = Config->Rela ? ".rela.plt" : ".rel.plt"; + StringRef S = llvm::StringRef(Config->Rela ? ".rela.plt" : ".rel.plt"); GotPlt.reset(new GotPltSection); RelaPlt.reset(new RelocationSection(S, false /*Sort*/)); if (Config->Strip != StripPolicy::All) { @@ -574,10 +577,11 @@ template void Writer::addRelIpltSymbols() { if (Out::DynSymTab || !Out::RelaPlt) return; - StringRef S = Config->Rela ? "__rela_iplt_start" : "__rel_iplt_start"; + StringRef S = + llvm::StringRef(Config->Rela ? "__rela_iplt_start" : "__rel_iplt_start"); addOptionalSynthetic(S, Out::RelaPlt, 0); - S = Config->Rela ? "__rela_iplt_end" : "__rel_iplt_end"; + S = llvm::StringRef(Config->Rela ? "__rela_iplt_end" : "__rel_iplt_end"); addOptionalSynthetic(S, Out::RelaPlt, DefinedSynthetic::SectionEnd); } Index: lld/lib/ReaderWriter/MachO/LayoutPass.cpp =================================================================== --- lld/lib/ReaderWriter/MachO/LayoutPass.cpp +++ lld/lib/ReaderWriter/MachO/LayoutPass.cpp @@ -252,7 +252,7 @@ std::string reason; bool result = compareAtomsSub(lc, rc, customSorter, reason); DEBUG({ - StringRef comp = result ? "<" : ">="; + StringRef comp(result ? "<" : ">="); llvm::dbgs() << "Layout: '" << lc._atom.get()->name() << "' " << comp << " '" << rc._atom.get()->name() << "' (" << reason << ")\n"; Index: lld/lib/ReaderWriter/MachO/MachOLinkingContext.cpp =================================================================== --- lld/lib/ReaderWriter/MachO/MachOLinkingContext.cpp +++ lld/lib/ReaderWriter/MachO/MachOLinkingContext.cpp @@ -393,7 +393,7 @@ } StringRef MachOLinkingContext::binderSymbolName() const { - return archHandler().stubInfo().binderSymbolName; + return llvm::StringRef(archHandler().stubInfo().binderSymbolName); } bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const { Index: lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryReader.cpp =================================================================== --- lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryReader.cpp +++ lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryReader.cpp @@ -389,7 +389,7 @@ Symbol sout; if (sin->n_strx > strSize) return true; - sout.name = &strings[sin->n_strx]; + sout.name = llvm::StringRef(&strings[sin->n_strx]); sout.type = static_cast(sin->n_type & (N_STAB|N_TYPE)); sout.scope = (sin->n_type & (N_PEXT|N_EXT)); sout.sect = sin->n_sect; @@ -421,7 +421,7 @@ Symbol sout; if (sin->n_strx > strSize) return true; - sout.name = &strings[sin->n_strx]; + sout.name = llvm::StringRef(&strings[sin->n_strx]); sout.type = (NListType)(sin->n_type & N_TYPE); sout.scope = (sin->n_type & (N_PEXT|N_EXT)); sout.sect = sin->n_sect; @@ -441,7 +441,7 @@ break; case LC_ID_DYLIB: { const dylib_command *dl = reinterpret_cast(lc); - f->installName = lc + read32(&dl->dylib.name, isBig); + f->installName = llvm::StringRef(lc + read32(&dl->dylib.name, isBig)); f->currentVersion = read32(&dl->dylib.current_version, isBig); f->compatVersion = read32(&dl->dylib.compatibility_version, isBig); } @@ -460,7 +460,7 @@ case LC_LOAD_UPWARD_DYLIB: { const dylib_command *dl = reinterpret_cast(lc); DependentDylib entry; - entry.path = lc + read32(&dl->dylib.name, isBig); + entry.path = llvm::StringRef(lc + read32(&dl->dylib.name, isBig)); entry.kind = LoadCommandType(cmd); entry.compatVersion = read32(&dl->dylib.compatibility_version, isBig); entry.currentVersion = read32(&dl->dylib.current_version, isBig); @@ -469,7 +469,7 @@ break; case LC_RPATH: { const rpath_command *rpc = reinterpret_cast(lc); - f->rpaths.push_back(lc + read32(&rpc->path, isBig)); + f->rpaths.push_back(llvm::StringRef(lc + read32(&rpc->path, isBig))); } break; case LC_DYLD_INFO: Index: lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryUtils.h =================================================================== --- lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryUtils.h +++ lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryUtils.h @@ -189,7 +189,7 @@ } inline StringRef getString16(const char s[16]) { - StringRef x = s; + StringRef x(s); if ( x.size() > 16 ) return x.substr(0, 16); else Index: lld/lib/ReaderWriter/MachO/MachONormalizedFileFromAtoms.cpp =================================================================== --- lld/lib/ReaderWriter/MachO/MachONormalizedFileFromAtoms.cpp +++ lld/lib/ReaderWriter/MachO/MachONormalizedFileFromAtoms.cpp @@ -875,7 +875,7 @@ memcpy(p, newDirPath.data(), newDirPath.size()); p[newDirPath.size()] = '/'; p[newDirPath.size() + 1] = '\0'; - newDirPath = p; + newDirPath = StringRef(p, newDirPath.size() + 1); } // New translation unit, emit start SOs: @@ -900,7 +900,7 @@ modTime = stat.getLastModificationTime().toEpochTime(); _stabs.push_back(mach_o::Stab(nullptr, N_OSO, _ctx.getCPUSubType(), 1, - modTime, fullPath)); + modTime, StringRef(fullPath))); // linker should put cpusubtype in n_sect field // of nlist entry for N_OSO debug note entries. wroteStartSO = true; Index: lld/lib/ReaderWriter/MachO/MachONormalizedFileToAtoms.cpp =================================================================== --- lld/lib/ReaderWriter/MachO/MachONormalizedFileToAtoms.cpp +++ lld/lib/ReaderWriter/MachO/MachONormalizedFileToAtoms.cpp @@ -705,7 +705,7 @@ char *strCopy = alloc.Allocate(str.size() + 1); memcpy(strCopy, str.data(), str.size()); strCopy[str.size()] = '\0'; - return strCopy; + return llvm::StringRef(strCopy); } llvm::Error parseStabs(MachOFile &file, @@ -911,7 +911,7 @@ case llvm::dwarf::DW_AT_name: { if (auto eName = getIndexedString(normalizedFile, form, infoData, offset, strings)) - tu.name = *eName; + tu.name = llvm::StringRef(*eName); else return eName.takeError(); break; @@ -919,7 +919,7 @@ case llvm::dwarf::DW_AT_comp_dir: { if (auto eName = getIndexedString(normalizedFile, form, infoData, offset, strings)) - tu.path = *eName; + tu.path = llvm::StringRef(*eName); else return eName.takeError(); break; Index: lld/lib/ReaderWriter/MachO/StubsPass.cpp =================================================================== --- lld/lib/ReaderWriter/MachO/StubsPass.cpp +++ lld/lib/ReaderWriter/MachO/StubsPass.cpp @@ -271,11 +271,12 @@ mergedFile.addAtom(*helperCacheNLPAtom); // Add reference to dyld_stub_binder in libSystem.dylib - auto I = std::find_if( - mergedFile.sharedLibrary().begin(), mergedFile.sharedLibrary().end(), - [&](const SharedLibraryAtom *atom) { - return atom->name().equals(_stubInfo.binderSymbolName); - }); + auto I = std::find_if(mergedFile.sharedLibrary().begin(), + mergedFile.sharedLibrary().end(), + [&](const SharedLibraryAtom *atom) { + return atom->name().equals( + llvm::StringRef(_stubInfo.binderSymbolName)); + }); assert(I != mergedFile.sharedLibrary().end() && "dyld_stub_binder not found"); addReference(helperBinderNLPAtom, _stubInfo.nonLazyPointerReferenceToBinder, *I); Index: lld/tools/lld/lld.cpp =================================================================== --- lld/tools/lld/lld.cpp +++ lld/tools/lld/lld.cpp @@ -94,7 +94,7 @@ /// windows linker based on the argv[0] or -flavor option. int main(int Argc, const char **Argv) { // Standard set up, so program fails gracefully. - sys::PrintStackTraceOnErrorSignal(Argv[0]); + sys::PrintStackTraceOnErrorSignal(llvm::StringRef(Argv[0])); PrettyStackTraceProgram StackPrinter(Argc, Argv); llvm_shutdown_obj Shutdown; Index: lldb/include/lldb/Expression/IRExecutionUnit.h =================================================================== --- lldb/include/lldb/Expression/IRExecutionUnit.h +++ lldb/include/lldb/Expression/IRExecutionUnit.h @@ -82,8 +82,9 @@ llvm::Module *GetModule() { return m_module; } llvm::Function *GetFunction() { - return ((m_module != nullptr) ? m_module->getFunction(m_name.AsCString()) - : nullptr); + return ((m_module != nullptr) + ? m_module->getFunction(llvm::StringRef(m_name.AsCString())) + : nullptr); } void GetRunnableInfo(Error &error, lldb::addr_t &func_addr, Index: lldb/include/lldb/Interpreter/CommandObject.h =================================================================== --- lldb/include/lldb/Interpreter/CommandObject.h +++ lldb/include/lldb/Interpreter/CommandObject.h @@ -467,7 +467,8 @@ CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help = nullptr, const char *syntax = nullptr, uint32_t flags = 0) - : CommandObject(interpreter, name, help, syntax, flags) {} + : CommandObject(interpreter, llvm::StringRef(name), llvm::StringRef(help), + llvm::StringRef(syntax), flags) {} ~CommandObjectParsed() override = default; Index: lldb/include/lldb/Symbol/ClangASTContext.h =================================================================== --- lldb/include/lldb/Symbol/ClangASTContext.h +++ lldb/include/lldb/Symbol/ClangASTContext.h @@ -220,7 +220,7 @@ clang::ASTContext *ast = getASTContext(); if (ast) { clang::IdentifierInfo &myIdent = - ast->Idents.get(type_name.GetCString()); + ast->Idents.get(llvm::StringRef(type_name.GetCString())); clang::DeclarationName myName = ast->DeclarationNames.getIdentifier(&myIdent); Index: lldb/include/lldb/Target/Process.h =================================================================== --- lldb/include/lldb/Target/Process.h +++ lldb/include/lldb/Target/Process.h @@ -317,7 +317,8 @@ NameMatchType process_name_match_type) : m_match_info(), m_name_match_type(process_name_match_type), m_match_all_users(false) { - m_match_info.GetExecutableFile().SetFile(process_name, false); + m_match_info.GetExecutableFile().SetFile(llvm::StringRef(process_name), + false); } ProcessInstanceInfo &GetProcessInfo() { return m_match_info; } Index: lldb/include/lldb/Utility/AnsiTerminal.h =================================================================== --- lldb/include/lldb/Utility/AnsiTerminal.h +++ lldb/include/lldb/Utility/AnsiTerminal.h @@ -64,7 +64,7 @@ // Convert "${ansi.XXX}" tokens to ansi values or clear them if do_color is // false. static const struct { - const char *name; + const llvm::StringRef name; const char *value; } g_color_tokens[] = { #define _TO_STR2(_val) #_val Index: lldb/source/API/SBAttachInfo.cpp =================================================================== --- lldb/source/API/SBAttachInfo.cpp +++ lldb/source/API/SBAttachInfo.cpp @@ -26,14 +26,14 @@ SBAttachInfo::SBAttachInfo(const char *path, bool wait_for) : m_opaque_sp(new ProcessAttachInfo()) { if (path && path[0]) - m_opaque_sp->GetExecutableFile().SetFile(path, false); + m_opaque_sp->GetExecutableFile().SetFile(llvm::StringRef(path), false); m_opaque_sp->SetWaitForLaunch(wait_for); } SBAttachInfo::SBAttachInfo(const char *path, bool wait_for, bool async) : m_opaque_sp(new ProcessAttachInfo()) { if (path && path[0]) - m_opaque_sp->GetExecutableFile().SetFile(path, false); + m_opaque_sp->GetExecutableFile().SetFile(llvm::StringRef(path), false); m_opaque_sp->SetWaitForLaunch(wait_for); m_opaque_sp->SetAsync(async); } @@ -77,7 +77,7 @@ void SBAttachInfo::SetExecutable(const char *path) { if (path && path[0]) - m_opaque_sp->GetExecutableFile().SetFile(path, false); + m_opaque_sp->GetExecutableFile().SetFile(llvm::StringRef(path), false); else m_opaque_sp->GetExecutableFile().Clear(); } Index: lldb/source/API/SBCommandInterpreter.cpp =================================================================== --- lldb/source/API/SBCommandInterpreter.cpp +++ lldb/source/API/SBCommandInterpreter.cpp @@ -148,13 +148,15 @@ bool SBCommandInterpreter::IsValid() const { return m_opaque_ptr != nullptr; } bool SBCommandInterpreter::CommandExists(const char *cmd) { - return (((cmd != nullptr) && IsValid()) ? m_opaque_ptr->CommandExists(cmd) - : false); + return (((cmd != nullptr) && IsValid()) + ? m_opaque_ptr->CommandExists(llvm::StringRef(cmd)) + : false); } bool SBCommandInterpreter::AliasExists(const char *cmd) { - return (((cmd != nullptr) && IsValid()) ? m_opaque_ptr->AliasExists(cmd) - : false); + return (((cmd != nullptr) && IsValid()) + ? m_opaque_ptr->AliasExists(llvm::StringRef(cmd)) + : false); } bool SBCommandInterpreter::IsActive() { @@ -481,7 +483,7 @@ const char *command_name, lldb::CommandOverrideCallback callback, void *baton) { if (command_name && command_name[0] && IsValid()) { - llvm::StringRef command_name_str = command_name; + llvm::StringRef command_name_str = llvm::StringRef(command_name); CommandObject *cmd_obj = m_opaque_ptr->GetCommandObjectForCommand(command_name_str); if (cmd_obj) { @@ -500,7 +502,7 @@ new_command->SetRemovable(true); lldb::CommandObjectSP new_command_sp(new_command); if (new_command_sp && - m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) + m_opaque_ptr->AddUserCommand(llvm::StringRef(name), new_command_sp, true)) return lldb::SBCommand(new_command_sp); return lldb::SBCommand(); } @@ -512,7 +514,7 @@ *m_opaque_ptr, name, impl, help)); if (new_command_sp && - m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) + m_opaque_ptr->AddUserCommand(llvm::StringRef(name), new_command_sp, true)) return lldb::SBCommand(new_command_sp); return lldb::SBCommand(); } @@ -526,7 +528,7 @@ *m_opaque_ptr, name, impl, help, syntax)); if (new_command_sp && - m_opaque_ptr->AddUserCommand(name, new_command_sp, true)) + m_opaque_ptr->AddUserCommand(llvm::StringRef(name), new_command_sp, true)) return lldb::SBCommand(new_command_sp); return lldb::SBCommand(); } Index: lldb/source/API/SBDebugger.cpp =================================================================== --- lldb/source/API/SBDebugger.cpp +++ lldb/source/API/SBDebugger.cpp @@ -682,7 +682,8 @@ m_opaque_sp->GetPlatformList().GetSelectedPlatform().get()); TargetSP target_sp( m_opaque_sp->GetTargetList().FindTargetWithExecutableAndArchitecture( - FileSpec(filename, false), arch_name ? &arch : nullptr)); + FileSpec(llvm::StringRef(filename), false), + arch_name ? &arch : nullptr)); sb_target.SetSP(target_sp); } return sb_target; Index: lldb/source/API/SBFileSpec.cpp =================================================================== --- lldb/source/API/SBFileSpec.cpp +++ lldb/source/API/SBFileSpec.cpp @@ -31,10 +31,10 @@ // Deprecated!!! SBFileSpec::SBFileSpec(const char *path) - : m_opaque_ap(new FileSpec(path, true)) {} + : m_opaque_ap(new FileSpec(llvm::StringRef(path), true)) {} SBFileSpec::SBFileSpec(const char *path, bool resolve) - : m_opaque_ap(new FileSpec(path, resolve)) {} + : m_opaque_ap(new FileSpec(llvm::StringRef(path), resolve)) {} SBFileSpec::~SBFileSpec() {} @@ -65,7 +65,7 @@ int SBFileSpec::ResolvePath(const char *src_path, char *dst_path, size_t dst_len) { - llvm::SmallString<64> result(src_path); + llvm::SmallString<64> result((llvm::StringRef(src_path))); lldb_private::FileSpec::Resolve(result); ::snprintf(dst_path, dst_len, "%s", result.c_str()); return std::min(dst_len - 1, result.size()); @@ -162,5 +162,5 @@ } void SBFileSpec::AppendPathComponent(const char *fn) { - m_opaque_ap->AppendPathComponent(fn); + m_opaque_ap->AppendPathComponent(llvm::StringRef(fn)); } Index: lldb/source/API/SBHostOS.cpp =================================================================== --- lldb/source/API/SBHostOS.cpp +++ lldb/source/API/SBHostOS.cpp @@ -51,7 +51,7 @@ llvm::SmallString<64> home_dir_path; llvm::sys::path::home_directory(home_dir_path); - FileSpec homedir(home_dir_path.c_str(), true); + FileSpec homedir(llvm::StringRef(home_dir_path.c_str()), true); sb_fspec.SetFileSpec(homedir); return sb_fspec; @@ -73,7 +73,8 @@ // FIXME: You should log the return value? HostThread thread(ThreadLauncher::LaunchThread( - name, thread_function, thread_arg, error_ptr ? error_ptr->get() : NULL)); + llvm::StringRef(name), thread_function, thread_arg, + error_ptr ? error_ptr->get() : NULL)); return thread.Release(); } Index: lldb/source/API/SBLaunchInfo.cpp =================================================================== --- lldb/source/API/SBLaunchInfo.cpp +++ lldb/source/API/SBLaunchInfo.cpp @@ -109,7 +109,8 @@ } void SBLaunchInfo::SetWorkingDirectory(const char *working_dir) { - m_opaque_sp->SetWorkingDirectory(FileSpec{working_dir, false}); + m_opaque_sp->SetWorkingDirectory( + FileSpec{llvm::StringRef(working_dir), false}); } uint32_t SBLaunchInfo::GetLaunchFlags() { @@ -136,7 +137,7 @@ } void SBLaunchInfo::SetShell(const char *path) { - m_opaque_sp->SetShell(FileSpec(path, false)); + m_opaque_sp->SetShell(FileSpec(llvm::StringRef(path), false)); } bool SBLaunchInfo::GetShellExpandArguments() { @@ -165,8 +166,8 @@ bool SBLaunchInfo::AddOpenFileAction(int fd, const char *path, bool read, bool write) { - return m_opaque_sp->AppendOpenFileAction(fd, FileSpec{path, false}, read, - write); + return m_opaque_sp->AppendOpenFileAction( + fd, FileSpec{llvm::StringRef(path), false}, read, write); } bool SBLaunchInfo::AddSuppressFileAction(int fd, bool read, bool write) { Index: lldb/source/API/SBModuleSpec.cpp =================================================================== --- lldb/source/API/SBModuleSpec.cpp +++ lldb/source/API/SBModuleSpec.cpp @@ -113,7 +113,7 @@ SBModuleSpecList SBModuleSpecList::GetModuleSpecifications(const char *path) { SBModuleSpecList specs; - FileSpec file_spec(path, true); + FileSpec file_spec(llvm::StringRef(path), true); Host::ResolveExecutableInBundle(file_spec); ObjectFile::GetModuleSpecifications(file_spec, 0, 0, *specs.m_opaque_ap); return specs; Index: lldb/source/API/SBPlatform.cpp =================================================================== --- lldb/source/API/SBPlatform.cpp +++ lldb/source/API/SBPlatform.cpp @@ -238,7 +238,7 @@ PlatformSP platform_sp(GetSP()); if (platform_sp) { if (path) - platform_sp->SetWorkingDirectory(FileSpec{path, false}); + platform_sp->SetWorkingDirectory(FileSpec{llvm::StringRef(path), false}); else platform_sp->SetWorkingDirectory(FileSpec{}); return true; @@ -404,7 +404,7 @@ shell_command.SetWorkingDirectory(working_dir); } return platform_sp->RunShellCommand( - command, FileSpec{working_dir, false}, + command, FileSpec{llvm::StringRef(working_dir), false}, &shell_command.m_opaque_ptr->m_status, &shell_command.m_opaque_ptr->m_signo, &shell_command.m_opaque_ptr->m_output, @@ -443,8 +443,8 @@ SBError sb_error; PlatformSP platform_sp(GetSP()); if (platform_sp) { - sb_error.ref() = - platform_sp->MakeDirectory(FileSpec{path, false}, file_permissions); + sb_error.ref() = platform_sp->MakeDirectory( + FileSpec{llvm::StringRef(path), false}, file_permissions); } else { sb_error.SetErrorString("invalid platform"); } @@ -455,7 +455,8 @@ PlatformSP platform_sp(GetSP()); if (platform_sp) { uint32_t file_permissions = 0; - platform_sp->GetFilePermissions(FileSpec{path, false}, file_permissions); + platform_sp->GetFilePermissions(FileSpec{llvm::StringRef(path), false}, + file_permissions); return file_permissions; } return 0; @@ -466,8 +467,8 @@ SBError sb_error; PlatformSP platform_sp(GetSP()); if (platform_sp) { - sb_error.ref() = platform_sp->SetFilePermissions(FileSpec{path, false}, - file_permissions); + sb_error.ref() = platform_sp->SetFilePermissions( + FileSpec{llvm::StringRef(path), false}, file_permissions); } else { sb_error.SetErrorString("invalid platform"); } Index: lldb/source/API/SBProcess.cpp =================================================================== --- lldb/source/API/SBProcess.cpp +++ lldb/source/API/SBProcess.cpp @@ -129,9 +129,10 @@ if (stop_at_entry) launch_flags |= eLaunchFlagStopAtEntry; ProcessLaunchInfo launch_info( - FileSpec{stdin_path, false}, FileSpec{stdout_path, false}, - FileSpec{stderr_path, false}, FileSpec{working_directory, false}, - launch_flags); + FileSpec{llvm::StringRef(stdin_path), false}, + FileSpec{llvm::StringRef(stdout_path), false}, + FileSpec{llvm::StringRef(stderr_path), false}, + FileSpec{llvm::StringRef(working_directory), false}, launch_flags); Module *exe_module = process_sp->GetTarget().GetExecutableModulePointer(); if (exe_module) launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true); @@ -1268,7 +1269,7 @@ return error; } - FileSpec core_file(file_name, false); + FileSpec core_file(llvm::StringRef(file_name), false); error.ref() = PluginManager::SaveCore(process_sp, core_file); return error; } Index: lldb/source/API/SBTarget.cpp =================================================================== --- lldb/source/API/SBTarget.cpp +++ lldb/source/API/SBTarget.cpp @@ -184,7 +184,7 @@ SBProcess sb_process; TargetSP target_sp(GetSP()); if (target_sp) { - FileSpec filespec(core_file, true); + FileSpec filespec(llvm::StringRef(core_file), true); ProcessSP process_sp(target_sp->CreateProcess( target_sp->GetDebugger().GetListener(), NULL, &filespec)); if (process_sp) { @@ -279,9 +279,10 @@ launch_flags |= eLaunchFlagDisableSTDIO; ProcessLaunchInfo launch_info( - FileSpec{stdin_path, false}, FileSpec{stdout_path, false}, - FileSpec{stderr_path, false}, FileSpec{working_directory, false}, - launch_flags); + FileSpec{llvm::StringRef(stdin_path), false}, + FileSpec{llvm::StringRef(stdout_path), false}, + FileSpec{llvm::StringRef(stderr_path), false}, + FileSpec{llvm::StringRef(working_directory), false}, launch_flags); Module *exe_module = target_sp->GetExecutableModulePointer(); if (exe_module) @@ -478,7 +479,7 @@ if (name && target_sp) { ProcessAttachInfo attach_info; - attach_info.GetExecutableFile().SetFile(name, false); + attach_info.GetExecutableFile().SetFile(llvm::StringRef(name), false); attach_info.SetWaitForLaunch(wait_for); if (listener.IsValid()) attach_info.SetListener(listener.GetSP()); @@ -719,7 +720,7 @@ const lldb::addr_t offset = 0; if (module_name && module_name[0]) { FileSpecList module_spec_list; - module_spec_list.Append(FileSpec(module_name, false)); + module_spec_list.Append(FileSpec(llvm::StringRef(module_name), false)); *sb_bp = target_sp->CreateBreakpoint( &module_spec_list, NULL, symbol_name, eFunctionNameTypeAuto, eLanguageTypeUnknown, offset, skip_prologue, internal, hardware); @@ -846,7 +847,7 @@ SBFileSpecList module_spec_list; SBFileSpecList comp_unit_list; if (module_name && module_name[0]) { - module_spec_list.Append(FileSpec(module_name, false)); + module_spec_list.Append(FileSpec(llvm::StringRef(module_name), false)); } return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown, module_spec_list, comp_unit_list); @@ -947,7 +948,7 @@ SBFileSpecList module_spec_list; if (module_name && module_name[0]) { - module_spec_list.Append(FileSpec(module_name, false)); + module_spec_list.Append(FileSpec(llvm::StringRef(module_name), false)); } SBFileSpecList source_file_list; @@ -1421,7 +1422,7 @@ if (target_sp) { ModuleSpec module_spec; if (path) - module_spec.GetFileSpec().SetFile(path, false); + module_spec.GetFileSpec().SetFile(llvm::StringRef(path), false); if (uuid_cstr) module_spec.GetUUID().SetFromCString(uuid_cstr); @@ -1433,7 +1434,7 @@ module_spec.GetArchitecture() = target_sp->GetArchitecture(); if (symfile) - module_spec.GetSymbolFileSpec().SetFile(symfile, false); + module_spec.GetSymbolFileSpec().SetFile(llvm::StringRef(symfile), false); sb_module.SetSP(target_sp->GetSharedModule(module_spec)); } @@ -1624,7 +1625,7 @@ true, true, *sb_sc_list); break; case eMatchTypeStartsWith: - regexstr = llvm::Regex::escape(name) + ".*"; + regexstr = llvm::Regex::escape(llvm::StringRef(name)) + ".*"; target_sp->GetImages().FindFunctions(RegularExpression(regexstr), true, true, true, *sb_sc_list); break; @@ -1810,7 +1811,7 @@ RegularExpression(name_ref), append, max_matches, variable_list); break; case eMatchTypeStartsWith: - regexstr = llvm::Regex::escape(name) + ".*"; + regexstr = llvm::Regex::escape(llvm::StringRef(name)) + ".*"; match_count = target_sp->GetImages().FindGlobalVariables( RegularExpression(regexstr), append, max_matches, variable_list); break; Index: lldb/source/API/SBThread.cpp =================================================================== --- lldb/source/API/SBThread.cpp +++ lldb/source/API/SBThread.cpp @@ -559,7 +559,7 @@ StructuredData::ObjectSP info_root_sp = thread->GetExtendedInfo(); if (info_root_sp) { StructuredData::ObjectSP node = - info_root_sp->GetObjectForDotSeparatedPath(path); + info_root_sp->GetObjectForDotSeparatedPath(llvm::StringRef(path)); if (node) { if (node->GetType() == StructuredData::Type::eTypeString) { strm.Printf("%s", node->GetAsString()->GetValue().c_str()); Index: lldb/source/Breakpoint/Breakpoint.cpp =================================================================== --- lldb/source/Breakpoint/Breakpoint.cpp +++ lldb/source/Breakpoint/Breakpoint.cpp @@ -90,38 +90,42 @@ names_array_sp->AddItem( StructuredData::StringSP(new StructuredData::String(name))); } - breakpoint_contents_sp->AddItem(Breakpoint::GetKey(OptionNames::Names), - names_array_sp); + breakpoint_contents_sp->AddItem( + llvm::StringRef(Breakpoint::GetKey(OptionNames::Names)), + names_array_sp); } breakpoint_contents_sp->AddBooleanItem( - Breakpoint::GetKey(OptionNames::Hardware), m_hardware); + llvm::StringRef(Breakpoint::GetKey(OptionNames::Hardware)), m_hardware); StructuredData::ObjectSP resolver_dict_sp( m_resolver_sp->SerializeToStructuredData()); if (!resolver_dict_sp) return StructuredData::ObjectSP(); - breakpoint_contents_sp->AddItem(BreakpointResolver::GetSerializationKey(), - resolver_dict_sp); + breakpoint_contents_sp->AddItem( + llvm::StringRef(BreakpointResolver::GetSerializationKey()), + resolver_dict_sp); StructuredData::ObjectSP filter_dict_sp( m_filter_sp->SerializeToStructuredData()); if (!filter_dict_sp) return StructuredData::ObjectSP(); - breakpoint_contents_sp->AddItem(SearchFilter::GetSerializationKey(), - filter_dict_sp); + breakpoint_contents_sp->AddItem( + llvm::StringRef(SearchFilter::GetSerializationKey()), filter_dict_sp); StructuredData::ObjectSP options_dict_sp( m_options_up->SerializeToStructuredData()); if (!options_dict_sp) return StructuredData::ObjectSP(); - breakpoint_contents_sp->AddItem(BreakpointOptions::GetSerializationKey(), - options_dict_sp); + breakpoint_contents_sp->AddItem( + llvm::StringRef(BreakpointOptions::GetSerializationKey()), + options_dict_sp); - breakpoint_dict_sp->AddItem(GetSerializationKey(), breakpoint_contents_sp); + breakpoint_dict_sp->AddItem(llvm::StringRef(GetSerializationKey()), + breakpoint_contents_sp); return breakpoint_dict_sp; } @@ -138,7 +142,8 @@ StructuredData::Dictionary *resolver_dict; bool success = breakpoint_dict->GetValueForKeyAsDictionary( - BreakpointResolver::GetSerializationKey(), resolver_dict); + llvm::StringRef(BreakpointResolver::GetSerializationKey()), + resolver_dict); if (!success) { error.SetErrorStringWithFormat( "Breakpoint data missing toplevel resolver key"); @@ -158,7 +163,7 @@ StructuredData::Dictionary *filter_dict; success = breakpoint_dict->GetValueForKeyAsDictionary( - SearchFilter::GetSerializationKey(), filter_dict); + llvm::StringRef(SearchFilter::GetSerializationKey()), filter_dict); SearchFilterSP filter_sp; if (!success) filter_sp.reset( @@ -177,7 +182,7 @@ std::unique_ptr options_up; StructuredData::Dictionary *options_dict; success = breakpoint_dict->GetValueForKeyAsDictionary( - BreakpointOptions::GetSerializationKey(), options_dict); + llvm::StringRef(BreakpointOptions::GetSerializationKey()), options_dict); if (success) { options_up = BreakpointOptions::CreateFromStructuredData( target, *options_dict, create_error); @@ -191,7 +196,7 @@ bool hardware = false; success = breakpoint_dict->GetValueForKeyAsBoolean( - Breakpoint::GetKey(OptionNames::Hardware), hardware); + llvm::StringRef(Breakpoint::GetKey(OptionNames::Hardware)), hardware); result_sp = target.CreateBreakpoint(filter_sp, resolver_sp, false, hardware, true); @@ -202,7 +207,7 @@ StructuredData::Array *names_array; success = breakpoint_dict->GetValueForKeyAsArray( - Breakpoint::GetKey(OptionNames::Names), names_array); + llvm::StringRef(Breakpoint::GetKey(OptionNames::Names)), names_array); if (success && names_array) { size_t num_names = names_array->GetSize(); for (size_t i = 0; i < num_names; i++) { @@ -230,8 +235,8 @@ StructuredData::Array *names_array; - bool success = - bkpt_dict->GetValueForKeyAsArray(GetKey(OptionNames::Names), names_array); + bool success = bkpt_dict->GetValueForKeyAsArray( + llvm::StringRef(GetKey(OptionNames::Names)), names_array); // If there are no names, it can't match these names; if (!success) return false; @@ -853,7 +858,7 @@ if (!m_kind_description.empty()) { if (level == eDescriptionLevelBrief) { - s->PutCString(GetBreakpointKind()); + s->PutCString(llvm::StringRef(GetBreakpointKind())); return; } else s->Printf("Kind: %s\n", GetBreakpointKind()); Index: lldb/source/Breakpoint/BreakpointIDList.cpp =================================================================== --- lldb/source/Breakpoint/BreakpointIDList.cpp +++ lldb/source/Breakpoint/BreakpointIDList.cpp @@ -57,7 +57,8 @@ } bool BreakpointIDList::AddBreakpointID(const char *bp_id_str) { - auto bp_id = BreakpointID::ParseCanonicalReference(bp_id_str); + auto bp_id = + BreakpointID::ParseCanonicalReference(llvm::StringRef(bp_id_str)); if (!bp_id.hasValue()) return false; @@ -81,7 +82,8 @@ bool BreakpointIDList::FindBreakpointID(const char *bp_id_str, size_t *position) const { - auto bp_id = BreakpointID::ParseCanonicalReference(bp_id_str); + auto bp_id = + BreakpointID::ParseCanonicalReference(llvm::StringRef(bp_id_str)); if (!bp_id.hasValue()) return false; @@ -95,7 +97,8 @@ return; for (uint32_t i = 0; i < array_size; ++i) { - auto bp_id = BreakpointID::ParseCanonicalReference(string_array[i]); + auto bp_id = + BreakpointID::ParseCanonicalReference(llvm::StringRef(string_array[i])); if (bp_id.hasValue()) m_breakpoint_ids.push_back(*bp_id); } @@ -128,7 +131,7 @@ for (size_t i = 0; i < num_old_args; ++i) { bool is_range = false; - current_arg = old_args.GetArgumentAtIndex(i); + current_arg = llvm::StringRef(old_args.GetArgumentAtIndex(i)); if (!allow_locations && current_arg.contains('.')) { result.AppendErrorWithFormat( "Breakpoint locations not allowed, saw location: %s.", @@ -154,17 +157,17 @@ names_found.insert(current_arg); } else if ((i + 2 < num_old_args) && BreakpointID::IsRangeIdentifier( - old_args.GetArgumentAtIndex(i + 1)) && + llvm::StringRef(old_args.GetArgumentAtIndex(i + 1))) && BreakpointID::IsValidIDExpression(current_arg) && BreakpointID::IsValidIDExpression( - old_args.GetArgumentAtIndex(i + 2))) { + llvm::StringRef(old_args.GetArgumentAtIndex(i + 2)))) { range_from = current_arg; - range_to = old_args.GetArgumentAtIndex(i + 2); + range_to = llvm::StringRef(old_args.GetArgumentAtIndex(i + 2)); is_range = true; i = i + 2; } else { // See if user has specified id.* - llvm::StringRef tmp_str = old_args.GetArgumentAtIndex(i); + llvm::StringRef tmp_str = llvm::StringRef(old_args.GetArgumentAtIndex(i)); size_t pos = tmp_str.find('.'); if (pos != llvm::StringRef::npos) { llvm::StringRef bp_id_str = tmp_str.substr(0, pos); Index: lldb/source/Breakpoint/BreakpointLocation.cpp =================================================================== --- lldb/source/Breakpoint/BreakpointLocation.cpp +++ lldb/source/Breakpoint/BreakpointLocation.cpp @@ -510,7 +510,8 @@ if (sc.function != nullptr) { s->EOL(); s->Indent("function = "); - s->PutCString(sc.function->GetName().AsCString("")); + s->PutCString( + llvm::StringRef(sc.function->GetName().AsCString(""))); } if (sc.line_entry.line > 0) { @@ -527,7 +528,8 @@ s->Indent("re-exported target = "); else s->Indent("symbol = "); - s->PutCString(sc.symbol->GetName().AsCString("")); + s->PutCString( + llvm::StringRef(sc.symbol->GetName().AsCString(""))); } } } Index: lldb/source/Breakpoint/BreakpointOptions.cpp =================================================================== --- lldb/source/Breakpoint/BreakpointOptions.cpp +++ lldb/source/Breakpoint/BreakpointOptions.cpp @@ -44,19 +44,20 @@ StructuredData::DictionarySP options_dict_sp( new StructuredData::Dictionary()); - options_dict_sp->AddBooleanItem(GetKey(OptionNames::StopOnError), - stop_on_error); + options_dict_sp->AddBooleanItem( + llvm::StringRef(GetKey(OptionNames::StopOnError)), stop_on_error); StructuredData::ArraySP user_source_sp(new StructuredData::Array()); for (size_t i = 0; i < num_strings; i++) { StructuredData::StringSP item_sp( new StructuredData::String(user_source[i])); user_source_sp->AddItem(item_sp); - options_dict_sp->AddItem(GetKey(OptionNames::UserSource), user_source_sp); + options_dict_sp->AddItem(llvm::StringRef(GetKey(OptionNames::UserSource)), + user_source_sp); } options_dict_sp->AddStringItem( - GetKey(OptionNames::Interpreter), + llvm::StringRef(GetKey(OptionNames::Interpreter)), ScriptInterpreter::LanguageToString(interpreter)); return options_dict_sp; } @@ -68,7 +69,8 @@ bool found_something = false; bool success = options_dict.GetValueForKeyAsBoolean( - GetKey(OptionNames::StopOnError), data_up->stop_on_error); + llvm::StringRef(GetKey(OptionNames::StopOnError)), + data_up->stop_on_error); if (success) found_something = true; @@ -76,7 +78,7 @@ std::string interpreter_str; ScriptLanguage interp_language; success = options_dict.GetValueForKeyAsString( - GetKey(OptionNames::Interpreter), interpreter_str); + llvm::StringRef(GetKey(OptionNames::Interpreter)), interpreter_str); if (!success) { error.SetErrorString("Missing command language value."); @@ -93,8 +95,8 @@ data_up->interpreter = interp_language; StructuredData::Array *user_source; - success = options_dict.GetValueForKeyAsArray(GetKey(OptionNames::UserSource), - user_source); + success = options_dict.GetValueForKeyAsArray( + llvm::StringRef(GetKey(OptionNames::UserSource)), user_source); if (success) { found_something = true; size_t num_elems = user_source->GetSize(); @@ -203,7 +205,7 @@ std::string condition_text; bool success = options_dict.GetValueForKeyAsBoolean( - GetKey(OptionNames::EnabledState), enabled); + llvm::StringRef(GetKey(OptionNames::EnabledState)), enabled); if (!success) { error.SetErrorStringWithFormat("%s key is not a boolean.", GetKey(OptionNames::EnabledState)); @@ -211,14 +213,14 @@ } success = options_dict.GetValueForKeyAsBoolean( - GetKey(OptionNames::OneShotState), one_shot); + llvm::StringRef(GetKey(OptionNames::OneShotState)), one_shot); if (!success) { error.SetErrorStringWithFormat("%s key is not a boolean.", GetKey(OptionNames::OneShotState)); return nullptr; } success = options_dict.GetValueForKeyAsInteger( - GetKey(OptionNames::IgnoreCount), ignore_count); + llvm::StringRef(GetKey(OptionNames::IgnoreCount)), ignore_count); if (!success) { error.SetErrorStringWithFormat("%s key is not an integer.", GetKey(OptionNames::IgnoreCount)); @@ -228,7 +230,7 @@ std::unique_ptr cmd_data_up; StructuredData::Dictionary *cmds_dict; success = options_dict.GetValueForKeyAsDictionary( - CommandData::GetSerializationKey(), cmds_dict); + llvm::StringRef(CommandData::GetSerializationKey()), cmds_dict); if (success && cmds_dict) { Error cmds_error; cmd_data_up = CommandData::CreateFromStructuredData(*cmds_dict, cmds_error); @@ -273,7 +275,7 @@ StructuredData::Dictionary *thread_spec_dict; success = options_dict.GetValueForKeyAsDictionary( - ThreadSpec::GetSerializationKey(), thread_spec_dict); + llvm::StringRef(ThreadSpec::GetSerializationKey()), thread_spec_dict); if (success) { Error thread_spec_error; std::unique_ptr thread_spec_up = @@ -293,13 +295,14 @@ StructuredData::ObjectSP BreakpointOptions::SerializeToStructuredData() { StructuredData::DictionarySP options_dict_sp( new StructuredData::Dictionary()); - options_dict_sp->AddBooleanItem(GetKey(OptionNames::EnabledState), m_enabled); - options_dict_sp->AddBooleanItem(GetKey(OptionNames::OneShotState), - m_one_shot); - options_dict_sp->AddIntegerItem(GetKey(OptionNames::IgnoreCount), - m_ignore_count); - options_dict_sp->AddStringItem(GetKey(OptionNames::ConditionText), - m_condition_text); + options_dict_sp->AddBooleanItem( + llvm::StringRef(GetKey(OptionNames::EnabledState)), m_enabled); + options_dict_sp->AddBooleanItem( + llvm::StringRef(GetKey(OptionNames::OneShotState)), m_one_shot); + options_dict_sp->AddIntegerItem( + llvm::StringRef(GetKey(OptionNames::IgnoreCount)), m_ignore_count); + options_dict_sp->AddStringItem( + llvm::StringRef(GetKey(OptionNames::ConditionText)), m_condition_text); if (m_baton_is_command_baton) { auto cmd_baton = std::static_pointer_cast(m_callback_baton_sp); @@ -307,13 +310,16 @@ cmd_baton->getItem()->SerializeToStructuredData(); if (commands_sp) { options_dict_sp->AddItem( - BreakpointOptions::CommandData::GetSerializationKey(), commands_sp); + llvm::StringRef( + BreakpointOptions::CommandData::GetSerializationKey()), + commands_sp); } } if (m_thread_spec_ap) { StructuredData::ObjectSP thread_spec_sp = m_thread_spec_ap->SerializeToStructuredData(); - options_dict_sp->AddItem(ThreadSpec::GetSerializationKey(), thread_spec_sp); + options_dict_sp->AddItem(llvm::StringRef(ThreadSpec::GetSerializationKey()), + thread_spec_sp); } return options_dict_sp; Index: lldb/source/Breakpoint/BreakpointResolver.cpp =================================================================== --- lldb/source/Breakpoint/BreakpointResolver.cpp +++ lldb/source/Breakpoint/BreakpointResolver.cpp @@ -82,7 +82,7 @@ std::string subclass_name; bool success = resolver_dict.GetValueForKeyAsString( - GetSerializationSubclassKey(), subclass_name); + llvm::StringRef(GetSerializationSubclassKey()), subclass_name); if (!success) { error.SetErrorStringWithFormat( @@ -99,7 +99,7 @@ StructuredData::Dictionary *subclass_options = nullptr; success = resolver_dict.GetValueForKeyAsDictionary( - GetSerializationSubclassOptionsKey(), subclass_options); + llvm::StringRef(GetSerializationSubclassOptionsKey()), subclass_options); if (!success || !subclass_options || !subclass_options->IsValid()) { error.SetErrorString("Resolver data missing subclass options key."); return result_sp; @@ -107,7 +107,7 @@ lldb::addr_t offset; success = subclass_options->GetValueForKeyAsInteger( - GetKey(OptionNames::Offset), offset); + llvm::StringRef(GetKey(OptionNames::Offset)), offset); if (!success) { error.SetErrorString("Resolver data missing offset options key."); return result_sp; @@ -154,11 +154,14 @@ return StructuredData::DictionarySP(); StructuredData::DictionarySP type_dict_sp(new StructuredData::Dictionary()); - type_dict_sp->AddStringItem(GetSerializationSubclassKey(), GetResolverName()); - type_dict_sp->AddItem(GetSerializationSubclassOptionsKey(), options_dict_sp); + type_dict_sp->AddStringItem(llvm::StringRef(GetSerializationSubclassKey()), + GetResolverName()); + type_dict_sp->AddItem(llvm::StringRef(GetSerializationSubclassOptionsKey()), + options_dict_sp); // Add the m_offset to the dictionary: - options_dict_sp->AddIntegerItem(GetKey(OptionNames::Offset), m_offset); + options_dict_sp->AddIntegerItem(llvm::StringRef(GetKey(OptionNames::Offset)), + m_offset); return type_dict_sp; } Index: lldb/source/Breakpoint/BreakpointResolverAddress.cpp =================================================================== --- lldb/source/Breakpoint/BreakpointResolverAddress.cpp +++ lldb/source/Breakpoint/BreakpointResolverAddress.cpp @@ -51,22 +51,23 @@ bool success; success = options_dict.GetValueForKeyAsInteger( - GetKey(OptionNames::AddressOffset), addr_offset); + llvm::StringRef(GetKey(OptionNames::AddressOffset)), addr_offset); if (!success) { error.SetErrorString("BRFL::CFSD: Couldn't find address offset entry."); return nullptr; } Address address(addr_offset); - success = options_dict.HasKey(GetKey(OptionNames::ModuleName)); + success = + options_dict.HasKey(llvm::StringRef(GetKey(OptionNames::ModuleName))); if (success) { success = options_dict.GetValueForKeyAsString( - GetKey(OptionNames::ModuleName), module_name); + llvm::StringRef(GetKey(OptionNames::ModuleName)), module_name); if (!success) { error.SetErrorString("BRA::CFSD: Couldn't read module name entry."); return nullptr; } - module_filespec.SetFile(module_name.c_str(), false); + module_filespec.SetFile(llvm::StringRef(module_name.c_str()), false); } return new BreakpointResolverAddress(bkpt, address, module_filespec); } @@ -82,16 +83,20 @@ if (module_sp) module_name.SetCString(module_name.GetCString()); - options_dict_sp->AddStringItem(GetKey(OptionNames::ModuleName), - module_name.GetCString()); - options_dict_sp->AddIntegerItem(GetKey(OptionNames::AddressOffset), - m_addr.GetOffset()); + options_dict_sp->AddStringItem( + llvm::StringRef(GetKey(OptionNames::ModuleName)), + module_name.GetCString()); + options_dict_sp->AddIntegerItem( + llvm::StringRef(GetKey(OptionNames::AddressOffset)), + m_addr.GetOffset()); } else { - options_dict_sp->AddIntegerItem(GetKey(OptionNames::AddressOffset), - m_addr.GetOffset()); + options_dict_sp->AddIntegerItem( + llvm::StringRef(GetKey(OptionNames::AddressOffset)), + m_addr.GetOffset()); if (m_module_filespec) { - options_dict_sp->AddStringItem(GetKey(OptionNames::ModuleName), - m_module_filespec.GetPath()); + options_dict_sp->AddStringItem( + llvm::StringRef(GetKey(OptionNames::ModuleName)), + m_module_filespec.GetPath()); } } Index: lldb/source/Breakpoint/BreakpointResolverFileLine.cpp =================================================================== --- lldb/source/Breakpoint/BreakpointResolverFileLine.cpp +++ lldb/source/Breakpoint/BreakpointResolverFileLine.cpp @@ -48,42 +48,42 @@ lldb::addr_t offset = 0; - success = options_dict.GetValueForKeyAsString(GetKey(OptionNames::FileName), - filename); + success = options_dict.GetValueForKeyAsString( + llvm::StringRef(GetKey(OptionNames::FileName)), filename); if (!success) { error.SetErrorString("BRFL::CFSD: Couldn't find filename entry."); return nullptr; } success = options_dict.GetValueForKeyAsInteger( - GetKey(OptionNames::LineNumber), line_no); + llvm::StringRef(GetKey(OptionNames::LineNumber)), line_no); if (!success) { error.SetErrorString("BRFL::CFSD: Couldn't find line number entry."); return nullptr; } - success = options_dict.GetValueForKeyAsBoolean(GetKey(OptionNames::Inlines), - check_inlines); + success = options_dict.GetValueForKeyAsBoolean( + llvm::StringRef(GetKey(OptionNames::Inlines)), check_inlines); if (!success) { error.SetErrorString("BRFL::CFSD: Couldn't find check inlines entry."); return nullptr; } success = options_dict.GetValueForKeyAsBoolean( - GetKey(OptionNames::SkipPrologue), skip_prologue); + llvm::StringRef(GetKey(OptionNames::SkipPrologue)), skip_prologue); if (!success) { error.SetErrorString("BRFL::CFSD: Couldn't find skip prologue entry."); return nullptr; } success = options_dict.GetValueForKeyAsBoolean( - GetKey(OptionNames::ExactMatch), exact_match); + llvm::StringRef(GetKey(OptionNames::ExactMatch)), exact_match); if (!success) { error.SetErrorString("BRFL::CFSD: Couldn't find exact match entry."); return nullptr; } - FileSpec file_spec(filename.c_str(), false); + FileSpec file_spec(llvm::StringRef(filename.c_str()), false); return new BreakpointResolverFileLine(bkpt, file_spec, line_no, offset, check_inlines, skip_prologue, @@ -95,15 +95,16 @@ StructuredData::DictionarySP options_dict_sp( new StructuredData::Dictionary()); - options_dict_sp->AddStringItem(GetKey(OptionNames::FileName), + options_dict_sp->AddStringItem(llvm::StringRef(GetKey(OptionNames::FileName)), m_file_spec.GetPath()); - options_dict_sp->AddIntegerItem(GetKey(OptionNames::LineNumber), - m_line_number); - options_dict_sp->AddBooleanItem(GetKey(OptionNames::Inlines), m_inlines); - options_dict_sp->AddBooleanItem(GetKey(OptionNames::SkipPrologue), - m_skip_prologue); - options_dict_sp->AddBooleanItem(GetKey(OptionNames::ExactMatch), - m_exact_match); + options_dict_sp->AddIntegerItem( + llvm::StringRef(GetKey(OptionNames::LineNumber)), m_line_number); + options_dict_sp->AddBooleanItem(llvm::StringRef(GetKey(OptionNames::Inlines)), + m_inlines); + options_dict_sp->AddBooleanItem( + llvm::StringRef(GetKey(OptionNames::SkipPrologue)), m_skip_prologue); + options_dict_sp->AddBooleanItem( + llvm::StringRef(GetKey(OptionNames::ExactMatch)), m_exact_match); return WrapOptionsDict(options_dict_sp); } Index: lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp =================================================================== --- lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp +++ lldb/source/Breakpoint/BreakpointResolverFileRegex.cpp @@ -42,7 +42,7 @@ std::string regex_string; success = options_dict.GetValueForKeyAsString( - GetKey(OptionNames::RegexString), regex_string); + llvm::StringRef(GetKey(OptionNames::RegexString)), regex_string); if (!success) { error.SetErrorString("BRFR::CFSD: Couldn't find regex entry."); return nullptr; @@ -51,7 +51,7 @@ bool exact_match; success = options_dict.GetValueForKeyAsBoolean( - GetKey(OptionNames::ExactMatch), exact_match); + llvm::StringRef(GetKey(OptionNames::ExactMatch)), exact_match); if (!success) { error.SetErrorString("BRFL::CFSD: Couldn't find exact match entry."); return nullptr; @@ -61,7 +61,7 @@ std::unordered_set names_set; StructuredData::Array *names_array; success = options_dict.GetValueForKeyAsArray( - GetKey(OptionNames::SymbolNameArray), names_array); + llvm::StringRef(GetKey(OptionNames::SymbolNameArray)), names_array); if (success && names_array) { size_t num_names = names_array->GetSize(); for (size_t i = 0; i < num_names; i++) { @@ -84,17 +84,18 @@ StructuredData::DictionarySP options_dict_sp( new StructuredData::Dictionary()); - options_dict_sp->AddStringItem(GetKey(OptionNames::RegexString), - m_regex.GetText()); - options_dict_sp->AddBooleanItem(GetKey(OptionNames::ExactMatch), - m_exact_match); + options_dict_sp->AddStringItem( + llvm::StringRef(GetKey(OptionNames::RegexString)), m_regex.GetText()); + options_dict_sp->AddBooleanItem( + llvm::StringRef(GetKey(OptionNames::ExactMatch)), m_exact_match); if (!m_function_names.empty()) { StructuredData::ArraySP names_array_sp(new StructuredData::Array()); for (std::string name : m_function_names) { StructuredData::StringSP item(new StructuredData::String(name)); names_array_sp->AddItem(item); } - options_dict_sp->AddItem(GetKey(OptionNames::LineNumber), names_array_sp); + options_dict_sp->AddItem(llvm::StringRef(GetKey(OptionNames::LineNumber)), + names_array_sp); } return WrapOptionsDict(options_dict_sp); Index: lldb/source/Breakpoint/BreakpointResolverName.cpp =================================================================== --- lldb/source/Breakpoint/BreakpointResolverName.cpp +++ lldb/source/Breakpoint/BreakpointResolverName.cpp @@ -96,7 +96,7 @@ LanguageType language = eLanguageTypeUnknown; std::string language_name; bool success = options_dict.GetValueForKeyAsString( - GetKey(OptionNames::LanguageName), language_name); + llvm::StringRef(GetKey(OptionNames::LanguageName)), language_name); if (success) { language = Language::GetLanguageTypeFromString(language_name); if (language == eLanguageTypeUnknown) { @@ -107,8 +107,8 @@ } lldb::addr_t offset = 0; - success = - options_dict.GetValueForKeyAsInteger(GetKey(OptionNames::Offset), offset); + success = options_dict.GetValueForKeyAsInteger( + llvm::StringRef(GetKey(OptionNames::Offset)), offset); if (!success) { error.SetErrorStringWithFormat("BRN::CFSD: Missing offset entry."); return nullptr; @@ -116,7 +116,7 @@ bool skip_prologue; success = options_dict.GetValueForKeyAsBoolean( - GetKey(OptionNames::SkipPrologue), skip_prologue); + llvm::StringRef(GetKey(OptionNames::SkipPrologue)), skip_prologue); if (!success) { error.SetErrorStringWithFormat("BRN::CFSD: Missing Skip prologue entry."); return nullptr; @@ -124,7 +124,7 @@ std::string regex_text; success = options_dict.GetValueForKeyAsString( - GetKey(OptionNames::RegexString), regex_text); + llvm::StringRef(GetKey(OptionNames::RegexString)), regex_text); if (success) { RegularExpression regex(regex_text); return new BreakpointResolverName(bkpt, regex, language, offset, @@ -132,14 +132,14 @@ } else { StructuredData::Array *names_array; success = options_dict.GetValueForKeyAsArray( - GetKey(OptionNames::SymbolNameArray), names_array); + llvm::StringRef(GetKey(OptionNames::SymbolNameArray)), names_array); if (!success) { error.SetErrorStringWithFormat("BRN::CFSD: Missing symbol names entry."); return nullptr; } StructuredData::Array *names_mask_array; success = options_dict.GetValueForKeyAsArray( - GetKey(OptionNames::NameMaskArray), names_mask_array); + llvm::StringRef(GetKey(OptionNames::NameMaskArray)), names_mask_array); if (!success) { error.SetErrorStringWithFormat( "BRN::CFSD: Missing symbol names mask entry."); @@ -193,8 +193,8 @@ new StructuredData::Dictionary()); if (m_regex.IsValid()) { - options_dict_sp->AddStringItem(GetKey(OptionNames::RegexString), - m_regex.GetText()); + options_dict_sp->AddStringItem( + llvm::StringRef(GetKey(OptionNames::RegexString)), m_regex.GetText()); } else { StructuredData::ArraySP names_sp(new StructuredData::Array()); StructuredData::ArraySP name_masks_sp(new StructuredData::Array()); @@ -204,15 +204,17 @@ name_masks_sp->AddItem(StructuredData::IntegerSP( new StructuredData::Integer(lookup.GetNameTypeMask()))); } - options_dict_sp->AddItem(GetKey(OptionNames::SymbolNameArray), names_sp); - options_dict_sp->AddItem(GetKey(OptionNames::NameMaskArray), name_masks_sp); + options_dict_sp->AddItem( + llvm::StringRef(GetKey(OptionNames::SymbolNameArray)), names_sp); + options_dict_sp->AddItem( + llvm::StringRef(GetKey(OptionNames::NameMaskArray)), name_masks_sp); } if (m_language != eLanguageTypeUnknown) options_dict_sp->AddStringItem( - GetKey(OptionNames::LanguageName), + llvm::StringRef(GetKey(OptionNames::LanguageName)), Language::GetNameForLanguageType(m_language)); - options_dict_sp->AddBooleanItem(GetKey(OptionNames::SkipPrologue), - m_skip_prologue); + options_dict_sp->AddBooleanItem( + llvm::StringRef(GetKey(OptionNames::SkipPrologue)), m_skip_prologue); return WrapOptionsDict(options_dict_sp); } Index: lldb/source/Commands/CommandCompletions.cpp =================================================================== --- lldb/source/Commands/CommandCompletions.cpp +++ lldb/source/Commands/CommandCompletions.cpp @@ -140,7 +140,7 @@ if (file_type == FileSpec::eFileTypeDirectory) isa_directory = true; else if (file_type == FileSpec::eFileTypeSymbolicLink) { - if (FileSpec(partial_name_copy, false).IsDirectory()) + if (FileSpec(llvm::StringRef(partial_name_copy), false).IsDirectory()) isa_directory = true; } @@ -273,8 +273,9 @@ parameters.end_ptr = end_ptr; parameters.baselen = baselen; - FileSpec::EnumerateDirectory(containing_part.c_str(), true, true, true, - DiskFilesOrDirectoriesCallback, ¶meters); + FileSpec::EnumerateDirectory(llvm::StringRef(containing_part.c_str()), true, + true, true, DiskFilesOrDirectoriesCallback, + ¶meters); return matches.GetSize(); } @@ -414,7 +415,7 @@ match_start_point, max_return_elements, matches), m_include_support_files(include_support_files), m_matching_files() { - FileSpec partial_spec(m_completion_str.c_str(), false); + FileSpec partial_spec(llvm::StringRef(m_completion_str.c_str()), false); m_file_name = partial_spec.GetFilename().GetCString(); m_dir_name = partial_spec.GetDirectory().GetCString(); } @@ -560,7 +561,7 @@ : CommandCompletions::Completer(interpreter, completion_str, match_start_point, max_return_elements, matches) { - FileSpec partial_spec(m_completion_str.c_str(), false); + FileSpec partial_spec(llvm::StringRef(m_completion_str.c_str()), false); m_file_name = partial_spec.GetFilename().GetCString(); m_dir_name = partial_spec.GetDirectory().GetCString(); } Index: lldb/source/Commands/CommandObjectBreakpoint.cpp =================================================================== --- lldb/source/Commands/CommandObjectBreakpoint.cpp +++ lldb/source/Commands/CommandObjectBreakpoint.cpp @@ -253,7 +253,8 @@ } break; case 'f': - m_filenames.AppendIfUnique(FileSpec(option_arg, false)); + m_filenames.AppendIfUnique( + FileSpec(llvm::StringRef(option_arg), false)); break; case 'F': @@ -376,7 +377,7 @@ break; case 's': - m_modules.AppendIfUnique(FileSpec(option_arg, false)); + m_modules.AppendIfUnique(FileSpec(llvm::StringRef(option_arg), false)); break; case 'S': @@ -2305,8 +2306,8 @@ } } Error error = target->SerializeBreakpointsToFile( - FileSpec(m_options.m_filename.c_str(), true), valid_bp_ids, - m_options.m_append); + FileSpec(llvm::StringRef(m_options.m_filename.c_str()), true), + valid_bp_ids, m_options.m_append); if (!error.Success()) { result.AppendErrorWithFormat("error serializing breakpoints: %s.", error.AsCString()); Index: lldb/source/Commands/CommandObjectBreakpointCommand.cpp =================================================================== --- lldb/source/Commands/CommandObjectBreakpointCommand.cpp +++ lldb/source/Commands/CommandObjectBreakpointCommand.cpp @@ -225,7 +225,7 @@ void IOHandlerActivated(IOHandler &io_handler) override { StreamFileSP output_sp(io_handler.GetOutputStreamFile()); if (output_sp) { - output_sp->PutCString(g_reader_instructions); + output_sp->PutCString(llvm::StringRef(g_reader_instructions)); output_sp->Flush(); } } Index: lldb/source/Commands/CommandObjectCommands.cpp =================================================================== --- lldb/source/Commands/CommandObjectCommands.cpp +++ lldb/source/Commands/CommandObjectCommands.cpp @@ -307,7 +307,7 @@ bool DoExecute(Args &command, CommandReturnObject &result) override { if (command.GetArgumentCount() == 1) { - llvm::StringRef filename = command.GetArgumentAtIndex(0); + llvm::StringRef filename = llvm::StringRef(command.GetArgumentAtIndex(0)); FileSpec cmd_file(filename, true); ExecutionContext *exe_ctx = nullptr; // Just use the default context. @@ -635,7 +635,7 @@ } // Verify that the command is alias-able. - if (m_interpreter.CommandExists(alias_command.c_str())) { + if (m_interpreter.CommandExists(llvm::StringRef(alias_command.c_str()))) { result.AppendErrorWithFormat( "'%s' is a permanent debugger command and cannot be redefined.\n", alias_command.c_str()); @@ -728,7 +728,7 @@ // Verify that the command is alias'able, and get the appropriate command // object. - if (m_interpreter.CommandExists(alias_command.c_str())) { + if (m_interpreter.CommandExists(llvm::StringRef(alias_command.c_str()))) { result.AppendErrorWithFormat( "'%s' is a permanent debugger command and cannot be redefined.\n", alias_command.c_str()); @@ -780,17 +780,18 @@ args.GetCommandString(args_string); } - if (m_interpreter.AliasExists(alias_command.c_str()) || - m_interpreter.UserCommandExists(alias_command.c_str())) { + if (m_interpreter.AliasExists(llvm::StringRef(alias_command.c_str())) || + m_interpreter.UserCommandExists( + llvm::StringRef(alias_command.c_str()))) { result.AppendWarningWithFormat( "Overwriting existing definition for '%s'.\n", alias_command.c_str()); } if (CommandAlias *alias = m_interpreter.AddAlias( - alias_command.c_str(), + llvm::StringRef(alias_command.c_str()), use_subcommand ? subcommand_obj_sp : command_obj_sp, - args_string.c_str())) { + llvm::StringRef(args_string.c_str()))) { if (m_command_options.m_help.OptionWasSet()) alias->SetHelp(m_command_options.m_help.GetCurrentValue()); if (m_command_options.m_long_help.OptionWasSet()) @@ -857,9 +858,9 @@ // dependent functions GetCommandObject, CommandExists, RemoveAlias, // AliasExists, etc. const char *command_name = args.GetArgumentAtIndex(0); - cmd_obj = m_interpreter.GetCommandObject(command_name); + cmd_obj = m_interpreter.GetCommandObject(llvm::StringRef(command_name)); if (cmd_obj) { - if (m_interpreter.CommandExists(command_name)) { + if (m_interpreter.CommandExists(llvm::StringRef(command_name))) { if (cmd_obj->IsRemovable()) { result.AppendErrorWithFormat( "'%s' is not an alias, it is a debugger command which can be " @@ -872,8 +873,8 @@ } result.SetStatus(eReturnStatusFailed); } else { - if (!m_interpreter.RemoveAlias(command_name)) { - if (m_interpreter.AliasExists(command_name)) + if (!m_interpreter.RemoveAlias(llvm::StringRef(command_name))) { + if (m_interpreter.AliasExists(llvm::StringRef(command_name))) result.AppendErrorWithFormat( "Error occurred while attempting to unalias '%s'.\n", command_name); @@ -938,8 +939,8 @@ // TODO: Convert this to accept a stringRef. const char *command_name = args.GetArgumentAtIndex(0); - if (m_interpreter.CommandExists(command_name)) { - if (m_interpreter.RemoveCommand(command_name)) { + if (m_interpreter.CommandExists(llvm::StringRef(command_name))) { + if (m_interpreter.RemoveCommand(llvm::StringRef(command_name))) { result.SetStatus(eReturnStatusSuccessFinishNoResult); } else { result.AppendErrorWithFormat( @@ -1074,9 +1075,10 @@ Error error; const char *name = command.GetArgumentAtIndex(0); - m_regex_cmd_ap.reset( - new CommandObjectRegexCommand(m_interpreter, name, m_options.GetHelp(), - m_options.GetSyntax(), 10, 0, true)); + m_regex_cmd_ap.reset(new CommandObjectRegexCommand( + m_interpreter, llvm::StringRef(name), + llvm::StringRef(m_options.GetHelp()), + llvm::StringRef(m_options.GetSyntax()), 10, 0, true)); if (argc == 1) { Debugger &debugger = m_interpreter.GetDebugger(); @@ -1688,7 +1690,7 @@ void IOHandlerActivated(IOHandler &io_handler) override { StreamFileSP output_sp(io_handler.GetOutputStreamFile()); if (output_sp) { - output_sp->PutCString(g_python_command_instructions); + output_sp->PutCString(llvm::StringRef(g_python_command_instructions)); output_sp->Flush(); } } @@ -1898,8 +1900,8 @@ const char *cmd_name = command.GetArgumentAtIndex(0); if (cmd_name && *cmd_name && m_interpreter.HasUserCommands() && - m_interpreter.UserCommandExists(cmd_name)) { - m_interpreter.RemoveUser(cmd_name); + m_interpreter.UserCommandExists(llvm::StringRef(cmd_name))) { + m_interpreter.RemoveUser(llvm::StringRef(cmd_name)); result.SetStatus(eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat("command %s not found", cmd_name); Index: lldb/source/Commands/CommandObjectFrame.cpp =================================================================== --- lldb/source/Commands/CommandObjectFrame.cpp +++ lldb/source/Commands/CommandObjectFrame.cpp @@ -695,7 +695,7 @@ continue; if (!scope_string.empty()) - s.PutCString(scope_string.c_str()); + s.PutCString(llvm::StringRef(scope_string.c_str())); if (m_option_variable.show_decl && var_sp->GetDeclaration().GetFile()) { Index: lldb/source/Commands/CommandObjectHelp.cpp =================================================================== --- lldb/source/Commands/CommandObjectHelp.cpp +++ lldb/source/Commands/CommandObjectHelp.cpp @@ -103,10 +103,10 @@ // Get command object for the first command argument. Only search built-in // command dictionary. StringList matches; - cmd_obj = - m_interpreter.GetCommandObject(command.GetArgumentAtIndex(0), &matches); - bool is_alias_command = - m_interpreter.AliasExists(command.GetArgumentAtIndex(0)); + cmd_obj = m_interpreter.GetCommandObject( + llvm::StringRef(command.GetArgumentAtIndex(0)), &matches); + bool is_alias_command = m_interpreter.AliasExists( + llvm::StringRef(command.GetArgumentAtIndex(0))); std::string alias_name = command.GetArgumentAtIndex(0); if (cmd_obj != nullptr) { @@ -220,8 +220,8 @@ input, cursor_index, cursor_char_position, match_start_point, max_return_elements, word_complete, matches); } else { - CommandObject *cmd_obj = - m_interpreter.GetCommandObject(input.GetArgumentAtIndex(0)); + CommandObject *cmd_obj = m_interpreter.GetCommandObject( + llvm::StringRef(input.GetArgumentAtIndex(0))); // The command that they are getting help on might be ambiguous, in which // case we should complete that, Index: lldb/source/Commands/CommandObjectLog.cpp =================================================================== --- lldb/source/Commands/CommandObjectLog.cpp +++ lldb/source/Commands/CommandObjectLog.cpp @@ -123,7 +123,7 @@ switch (short_option) { case 'f': - log_file.SetFile(option_arg, true); + log_file.SetFile(llvm::StringRef(option_arg), true); break; case 't': log_options |= LLDB_LOG_OPTION_THREADSAFE; @@ -350,7 +350,7 @@ result.SetStatus(eReturnStatusFailed); if (args.GetArgumentCount() == 1) { - llvm::StringRef sub_command = args.GetArgumentAtIndex(0); + llvm::StringRef sub_command = llvm::StringRef(args.GetArgumentAtIndex(0)); if (sub_command.equals_lower("enable")) { Timer::SetDisplayDepth(UINT32_MAX); @@ -367,8 +367,8 @@ result.SetStatus(eReturnStatusSuccessFinishResult); } } else if (args.GetArgumentCount() == 2) { - llvm::StringRef sub_command = args.GetArgumentAtIndex(0); - llvm::StringRef param = args.GetArgumentAtIndex(1); + llvm::StringRef sub_command = llvm::StringRef(args.GetArgumentAtIndex(0)); + llvm::StringRef param = llvm::StringRef(args.GetArgumentAtIndex(1)); if (sub_command.equals_lower("enable")) { uint32_t depth; Index: lldb/source/Commands/CommandObjectMultiword.cpp =================================================================== --- lldb/source/Commands/CommandObjectMultiword.cpp +++ lldb/source/Commands/CommandObjectMultiword.cpp @@ -29,7 +29,8 @@ const char *help, const char *syntax, uint32_t flags) - : CommandObject(interpreter, name, help, syntax, flags), + : CommandObject(interpreter, llvm::StringRef(name), llvm::StringRef(help), + llvm::StringRef(syntax), flags), m_can_be_removed(false) {} CommandObjectMultiword::~CommandObjectMultiword() = default; @@ -50,8 +51,8 @@ StringList local_matches; if (matches == nullptr) matches = &local_matches; - int num_matches = - AddNamesMatchingPartialString(m_subcommand_dict, sub_cmd, *matches); + int num_matches = AddNamesMatchingPartialString( + m_subcommand_dict, llvm::StringRef(sub_cmd), *matches); if (num_matches == 1) { // Cleaner, but slightly less efficient would be to call back into this @@ -94,7 +95,7 @@ bool CommandObjectMultiword::Execute(const char *args_string, CommandReturnObject &result) { - Args args(args_string); + Args args((llvm::StringRef(args_string))); const size_t argc = args.GetArgumentCount(); if (argc == 0) { this->CommandObject::GenerateHelpText(result); @@ -197,7 +198,8 @@ const char *arg0 = input.GetArgumentAtIndex(0); if (cursor_index == 0) { - AddNamesMatchingPartialString(m_subcommand_dict, arg0, matches); + AddNamesMatchingPartialString(m_subcommand_dict, llvm::StringRef(arg0), + matches); if (matches.GetSize() == 1 && matches.GetStringAtIndex(0) != nullptr && strcmp(arg0, matches.GetStringAtIndex(0)) == 0) { @@ -274,7 +276,8 @@ CommandObjectProxy::CommandObjectProxy(CommandInterpreter &interpreter, const char *name, const char *help, const char *syntax, uint32_t flags) - : CommandObject(interpreter, name, help, syntax, flags) {} + : CommandObject(interpreter, llvm::StringRef(name), llvm::StringRef(help), + llvm::StringRef(syntax), flags) {} CommandObjectProxy::~CommandObjectProxy() = default; Index: lldb/source/Commands/CommandObjectPlatform.cpp =================================================================== --- lldb/source/Commands/CommandObjectPlatform.cpp +++ lldb/source/Commands/CommandObjectPlatform.cpp @@ -550,7 +550,7 @@ perms = lldb::eFilePermissionsUserRW | lldb::eFilePermissionsGroupRW | lldb::eFilePermissionsWorldRead; lldb::user_id_t fd = platform_sp->OpenFile( - FileSpec(cmd_line.c_str(), false), + FileSpec(llvm::StringRef(cmd_line.c_str()), false), File::eOpenOptionRead | File::eOpenOptionWrite | File::eOpenOptionAppend | File::eOpenOptionCanCreate, perms, error); @@ -890,8 +890,9 @@ if (platform_sp) { const char *remote_file_path = args.GetArgumentAtIndex(0); const char *local_file_path = args.GetArgumentAtIndex(1); - Error error = platform_sp->GetFile(FileSpec(remote_file_path, false), - FileSpec(local_file_path, false)); + Error error = platform_sp->GetFile( + FileSpec(llvm::StringRef(remote_file_path), false), + FileSpec(llvm::StringRef(local_file_path), false)); if (error.Success()) { result.AppendMessageWithFormat( "successfully get-file from %s (remote) to %s (host)\n", @@ -956,8 +957,8 @@ m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); if (platform_sp) { std::string remote_file_path(args.GetArgumentAtIndex(0)); - user_id_t size = - platform_sp->GetFileSize(FileSpec(remote_file_path.c_str(), false)); + user_id_t size = platform_sp->GetFileSize( + FileSpec(llvm::StringRef(remote_file_path.c_str()), false)); if (size != UINT64_MAX) { result.AppendMessageWithFormat("File size of %s (remote): %" PRIu64 "\n", @@ -994,8 +995,9 @@ const char *src = args.GetArgumentAtIndex(0); const char *dst = args.GetArgumentAtIndex(1); - FileSpec src_fs(src, true); - FileSpec dst_fs(dst ? dst : src_fs.GetFilename().GetCString(), false); + FileSpec src_fs(llvm::StringRef(src), true); + FileSpec dst_fs( + llvm::StringRef(dst ? dst : src_fs.GetFilename().GetCString()), false); PlatformSP platform_sp( m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform()); @@ -1341,32 +1343,32 @@ } break; case 'n': - match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg, - false); + match_info.GetProcessInfo().GetExecutableFile().SetFile( + llvm::StringRef(option_arg), false); match_info.SetNameMatchType(eNameMatchEquals); break; case 'e': - match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg, - false); + match_info.GetProcessInfo().GetExecutableFile().SetFile( + llvm::StringRef(option_arg), false); match_info.SetNameMatchType(eNameMatchEndsWith); break; case 's': - match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg, - false); + match_info.GetProcessInfo().GetExecutableFile().SetFile( + llvm::StringRef(option_arg), false); match_info.SetNameMatchType(eNameMatchStartsWith); break; case 'c': - match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg, - false); + match_info.GetProcessInfo().GetExecutableFile().SetFile( + llvm::StringRef(option_arg), false); match_info.SetNameMatchType(eNameMatchContains); break; case 'r': - match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg, - false); + match_info.GetProcessInfo().GetExecutableFile().SetFile( + llvm::StringRef(option_arg), false); match_info.SetNameMatchType(eNameMatchRegularExpression); break; @@ -1536,7 +1538,8 @@ break; case 'n': - attach_info.GetExecutableFile().SetFile(option_arg, false); + attach_info.GetExecutableFile().SetFile(llvm::StringRef(option_arg), + false); break; case 'w': @@ -1586,7 +1589,7 @@ ProcessInstanceInfoMatch match_info; if (partial_name) { match_info.GetProcessInfo().GetExecutableFile().SetFile( - partial_name, false); + llvm::StringRef(partial_name), false); match_info.SetNameMatchType(eNameMatchStartsWith); } platform_sp->FindProcesses(match_info, process_infos); @@ -1793,7 +1796,7 @@ error = (platform_sp->RunShellCommand(expr, working_dir, &status, &signo, &output, m_options.timeout)); if (!output.empty()) - result.GetOutputStream().PutCString(output.c_str()); + result.GetOutputStream().PutCString(llvm::StringRef(output.c_str())); if (status > 0) { if (signo > 0) { const char *signo_cstr = Host::GetSignalAsCString(signo); @@ -1848,8 +1851,8 @@ return false; } // TODO: move the bulk of this code over to the platform itself - FileSpec src(args.GetArgumentAtIndex(0), true); - FileSpec dst(args.GetArgumentAtIndex(1), false); + FileSpec src(llvm::StringRef(args.GetArgumentAtIndex(0)), true); + FileSpec dst(llvm::StringRef(args.GetArgumentAtIndex(1)), false); if (!src.Exists()) { result.AppendError("source location does not exist or is not accessible"); result.SetStatus(eReturnStatusFailed); Index: lldb/source/Commands/CommandObjectPlugin.cpp =================================================================== --- lldb/source/Commands/CommandObjectPlugin.cpp +++ lldb/source/Commands/CommandObjectPlugin.cpp @@ -72,7 +72,7 @@ Error error; - FileSpec dylib_fspec(path, true); + FileSpec dylib_fspec(llvm::StringRef(path), true); if (m_interpreter.GetDebugger().LoadPlugin(dylib_fspec, error)) result.SetStatus(eReturnStatusSuccessFinishResult); Index: lldb/source/Commands/CommandObjectProcess.cpp =================================================================== --- lldb/source/Commands/CommandObjectProcess.cpp +++ lldb/source/Commands/CommandObjectProcess.cpp @@ -362,7 +362,8 @@ break; case 'n': - attach_info.GetExecutableFile().SetFile(option_arg, false); + attach_info.GetExecutableFile().SetFile(llvm::StringRef(option_arg), + false); break; case 'w': @@ -416,7 +417,7 @@ ProcessInstanceInfoMatch match_info; if (partial_name) { match_info.GetProcessInfo().GetExecutableFile().SetFile( - partial_name, false); + llvm::StringRef(partial_name), false); match_info.SetNameMatchType(eNameMatchStartsWith); } platform_sp->FindProcesses(match_info, process_infos); @@ -996,7 +997,7 @@ case 'i': do_install = true; if (option_arg && option_arg[0]) - install_path.SetFile(option_arg, false); + install_path.SetFile(llvm::StringRef(option_arg), false); break; default: error.SetErrorStringWithFormat("invalid short option character '%c'", @@ -1302,7 +1303,8 @@ ProcessSP process_sp = m_exe_ctx.GetProcessSP(); if (process_sp) { if (command.GetArgumentCount() == 1) { - FileSpec output_file(command.GetArgumentAtIndex(0), false); + FileSpec output_file(llvm::StringRef(command.GetArgumentAtIndex(0)), + false); Error error = PluginManager::SaveCore(process_sp, output_file); if (error.Success()) { result.SetStatus(eReturnStatusSuccessFinishResult); Index: lldb/source/Commands/CommandObjectSettings.cpp =================================================================== --- lldb/source/Commands/CommandObjectSettings.cpp +++ lldb/source/Commands/CommandObjectSettings.cpp @@ -183,7 +183,7 @@ protected: bool DoExecute(const char *command, CommandReturnObject &result) override { - Args cmd_args(command); + Args cmd_args((llvm::StringRef(command))); // Process possible options. if (!ParseOptions(cmd_args, result)) @@ -206,7 +206,8 @@ // Split the raw command into var_name and value pair. llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); + std::string var_value_string = + raw_str.split(llvm::StringRef(var_name)).second.str(); const char *var_value_cstr = Args::StripSpaces(var_value_string, true, false, false); @@ -468,7 +469,7 @@ bool DoExecute(const char *command, CommandReturnObject &result) override { result.SetStatus(eReturnStatusSuccessFinishNoResult); - Args cmd_args(command); + Args cmd_args((llvm::StringRef(command))); // Process possible options. if (!ParseOptions(cmd_args, result)) @@ -494,7 +495,8 @@ // Split the raw command into var_name and value pair. llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); + std::string var_value_string = + raw_str.split(llvm::StringRef(var_name)).second.str(); const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); @@ -591,7 +593,7 @@ bool DoExecute(const char *command, CommandReturnObject &result) override { result.SetStatus(eReturnStatusSuccessFinishNoResult); - Args cmd_args(command); + Args cmd_args((llvm::StringRef(command))); const char *var_name = cmd_args.GetArgumentAtIndex(0); if ((var_name == nullptr) || (var_name[0] == '\0')) { result.AppendError("'settings replace' command requires a valid variable " @@ -602,7 +604,8 @@ // Split the raw command into var_name, index_value, and value triple. llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); + std::string var_value_string = + raw_str.split(llvm::StringRef(var_name)).second.str(); const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); @@ -697,7 +700,7 @@ bool DoExecute(const char *command, CommandReturnObject &result) override { result.SetStatus(eReturnStatusSuccessFinishNoResult); - Args cmd_args(command); + Args cmd_args((llvm::StringRef(command))); const size_t argc = cmd_args.GetArgumentCount(); if (argc < 3) { @@ -716,7 +719,8 @@ // Split the raw command into var_name, index_value, and value triple. llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); + std::string var_value_string = + raw_str.split(llvm::StringRef(var_name)).second.str(); const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); @@ -808,7 +812,7 @@ bool DoExecute(const char *command, CommandReturnObject &result) override { result.SetStatus(eReturnStatusSuccessFinishNoResult); - Args cmd_args(command); + Args cmd_args((llvm::StringRef(command))); const size_t argc = cmd_args.GetArgumentCount(); if (argc < 3) { @@ -827,7 +831,8 @@ // Split the raw command into var_name, index_value, and value triple. llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); + std::string var_value_string = + raw_str.split(llvm::StringRef(var_name)).second.str(); const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); @@ -907,7 +912,7 @@ protected: bool DoExecute(const char *command, CommandReturnObject &result) override { result.SetStatus(eReturnStatusSuccessFinishNoResult); - Args cmd_args(command); + Args cmd_args((llvm::StringRef(command))); const size_t argc = cmd_args.GetArgumentCount(); if (argc < 2) { @@ -929,7 +934,8 @@ // Split the raw command into var_name and value pair. llvm::StringRef raw_str(command); - std::string var_value_string = raw_str.split(var_name).second.str(); + std::string var_value_string = + raw_str.split(llvm::StringRef(var_name)).second.str(); const char *var_value_cstr = Args::StripSpaces(var_value_string, true, true, false); Index: lldb/source/Commands/CommandObjectSource.cpp =================================================================== --- lldb/source/Commands/CommandObjectSource.cpp +++ lldb/source/Commands/CommandObjectSource.cpp @@ -609,7 +609,8 @@ m_module_list.Clear(); if (!m_options.modules.empty()) { for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) { - FileSpec module_file_spec(m_options.modules[i].c_str(), false); + FileSpec module_file_spec(llvm::StringRef(m_options.modules[i].c_str()), + false); if (module_file_spec) { ModuleSpec module_spec(module_file_spec); if (target->GetImages().FindModules(module_spec, m_module_list) == 0) @@ -944,7 +945,8 @@ if (num_modules > 0) { ModuleList matching_modules; for (size_t i = 0; i < num_modules; ++i) { - FileSpec module_file_spec(m_options.modules[i].c_str(), false); + FileSpec module_file_spec(llvm::StringRef(m_options.modules[i].c_str()), + false); if (module_file_spec) { ModuleSpec module_spec(module_file_spec); matching_modules.Clear(); @@ -969,7 +971,8 @@ if (num_modules > 0) { ModuleList matching_modules; for (size_t i = 0; i < num_modules; ++i) { - FileSpec module_file_spec(m_options.modules[i].c_str(), false); + FileSpec module_file_spec(llvm::StringRef(m_options.modules[i].c_str()), + false); if (module_file_spec) { ModuleSpec module_spec(module_file_spec); matching_modules.Clear(); @@ -1228,7 +1231,8 @@ if (!m_options.modules.empty()) { ModuleList matching_modules; for (size_t i = 0, e = m_options.modules.size(); i < e; ++i) { - FileSpec module_file_spec(m_options.modules[i].c_str(), false); + FileSpec module_file_spec( + llvm::StringRef(m_options.modules[i].c_str()), false); if (module_file_spec) { ModuleSpec module_spec(module_file_spec); matching_modules.Clear(); Index: lldb/source/Commands/CommandObjectSyntax.cpp =================================================================== --- lldb/source/Commands/CommandObjectSyntax.cpp +++ lldb/source/Commands/CommandObjectSyntax.cpp @@ -55,7 +55,8 @@ const size_t argc = command.GetArgumentCount(); if (argc > 0) { - cmd_obj = m_interpreter.GetCommandObject(command.GetArgumentAtIndex(0)); + cmd_obj = m_interpreter.GetCommandObject( + llvm::StringRef(command.GetArgumentAtIndex(0))); bool all_okay = true; // TODO: Convert to entry-based iteration. Requires converting // GetSubcommandObject. Index: lldb/source/Commands/CommandObjectTarget.cpp =================================================================== --- lldb/source/Commands/CommandObjectTarget.cpp +++ lldb/source/Commands/CommandObjectTarget.cpp @@ -252,7 +252,7 @@ FileSpec file_spec; if (file_path) - file_spec.SetFile(file_path, true); + file_spec.SetFile(llvm::StringRef(file_path), true); bool must_set_platform_path = false; @@ -1273,13 +1273,14 @@ if (full_triple) module->GetArchitecture().DumpTriple(arch_strm); else - arch_strm.PutCString(module->GetArchitecture().GetArchitectureName()); + arch_strm.PutCString( + llvm::StringRef(module->GetArchitecture().GetArchitectureName())); std::string arch_str = arch_strm.GetString(); if (width) strm.Printf("%-*s", width, arch_str.c_str()); else - strm.PutCString(arch_str.c_str()); + strm.PutCString(llvm::StringRef(arch_str.c_str())); } } @@ -1732,7 +1733,7 @@ static size_t FindModulesByName(Target *target, const char *module_name, ModuleList &module_list, bool check_global_list) { - FileSpec module_file_spec(module_name, false); + FileSpec module_file_spec(llvm::StringRef(module_name), false); ModuleSpec module_spec(module_file_spec); const size_t initial_size = module_list.GetSize(); @@ -2297,7 +2298,7 @@ for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != nullptr; ++arg_idx) { - FileSpec file_spec(arg_cstr, false); + FileSpec file_spec(llvm::StringRef(arg_cstr), false); const ModuleList &target_modules = target->GetImages(); std::lock_guard guard(target_modules.GetMutex()); @@ -3491,7 +3492,7 @@ break; case 'f': - m_file.SetFile(option_arg, false); + m_file.SetFile(llvm::StringRef(option_arg), false); m_type = eLookupTypeFileLine; break; Index: lldb/source/Commands/CommandObjectThread.cpp =================================================================== --- lldb/source/Commands/CommandObjectThread.cpp +++ lldb/source/Commands/CommandObjectThread.cpp @@ -1622,7 +1622,8 @@ switch (short_option) { case 'f': - m_filenames.AppendIfUnique(FileSpec(option_arg, false)); + m_filenames.AppendIfUnique( + FileSpec(llvm::StringRef(option_arg), false)); if (m_filenames.GetSize() > 1) return Error("only one source file expected."); break; Index: lldb/source/Commands/CommandObjectType.cpp =================================================================== --- lldb/source/Commands/CommandObjectType.cpp +++ lldb/source/Commands/CommandObjectType.cpp @@ -172,7 +172,7 @@ StreamFileSP output_sp(io_handler.GetOutputStreamFile()); if (output_sp) { - output_sp->PutCString(g_summary_addreader_instructions); + output_sp->PutCString(llvm::StringRef(g_summary_addreader_instructions)); output_sp->Flush(); } } @@ -418,7 +418,7 @@ void IOHandlerActivated(IOHandler &io_handler) override { StreamFileSP output_sp(io_handler.GetOutputStreamFile()); if (output_sp) { - output_sp->PutCString(g_synth_addreader_instructions); + output_sp->PutCString(llvm::StringRef(g_synth_addreader_instructions)); output_sp->Flush(); } } @@ -1198,7 +1198,8 @@ const lldb::TypeCategoryImplSP &category) -> bool { if (category_regex) { bool escape = true; - if (category->GetName() == category_regex->GetText()) { + if (llvm::StringRef(category->GetName()) == + category_regex->GetText()) { escape = false; } else if (category_regex->Execute( llvm::StringRef::withNullAsEmpty( @@ -2233,7 +2234,7 @@ [®ex, &result](const lldb::TypeCategoryImplSP &category_sp) -> bool { if (regex) { bool escape = true; - if (regex->GetText() == category_sp->GetName()) { + if (regex->GetText() == llvm::StringRef(category_sp->GetName())) { escape = false; } else if (regex->Execute(llvm::StringRef::withNullAsEmpty( category_sp->GetName()))) { Index: lldb/source/Commands/CommandObjectWatchpoint.cpp =================================================================== --- lldb/source/Commands/CommandObjectWatchpoint.cpp +++ lldb/source/Commands/CommandObjectWatchpoint.cpp @@ -69,7 +69,7 @@ uint32_t i; for (i = 0; i < 4; ++i) - if (Arg.find(RSA[i]) != llvm::StringRef::npos) + if (Arg.find(llvm::StringRef(RSA[i])) != llvm::StringRef::npos) return i; return -1; } @@ -104,7 +104,7 @@ continue; } // The Arg contains the range specifier, split it, then. - std::tie(first, second) = entry.ref.split(RSA[idx]); + std::tie(first, second) = entry.ref.split(llvm::StringRef(RSA[idx])); if (!first.empty()) StrRefArgs.push_back(first); StrRefArgs.push_back(Minus); @@ -1039,7 +1039,7 @@ Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); StackFrame *frame = m_exe_ctx.GetFramePtr(); - Args command(raw_command); + Args command((llvm::StringRef(raw_command))); const char *expr = nullptr; if (raw_command[0] == '-') { // We have some options and these options MUST end with --. Index: lldb/source/Core/Address.cpp =================================================================== --- lldb/source/Core/Address.cpp +++ lldb/source/Core/Address.cpp @@ -458,7 +458,7 @@ if (symbol) { const char *symbol_name = symbol->GetName().AsCString(); if (symbol_name) { - s->PutCString(symbol_name); + s->PutCString(llvm::StringRef(symbol_name)); addr_t delta = file_Addr - symbol->GetAddressRef().GetFileAddress(); if (delta) Index: lldb/source/Core/ArchSpec.cpp =================================================================== --- lldb/source/Core/ArchSpec.cpp +++ lldb/source/Core/ArchSpec.cpp @@ -512,7 +512,7 @@ // Get an architecture definition by name. static const CoreDefinition *FindCoreDefinition(llvm::StringRef name) { for (unsigned int i = 0; i < llvm::array_lengthof(g_core_definitions); ++i) { - if (name.equals_lower(g_core_definitions[i].name)) + if (name.equals_lower(llvm::StringRef(g_core_definitions[i].name))) return &g_core_definitions[i]; } return nullptr; Index: lldb/source/Core/Broadcaster.cpp =================================================================== --- lldb/source/Core/Broadcaster.cpp +++ lldb/source/Core/Broadcaster.cpp @@ -96,10 +96,10 @@ s.PutCString(", "); if (prefix_with_broadcaster_name) { - s.PutCString(GetBroadcasterName()); + s.PutCString(llvm::StringRef(GetBroadcasterName())); s.PutChar('.'); } - s.PutCString(pos->second.c_str()); + s.PutCString(llvm::StringRef(pos->second.c_str())); ++num_names_added; } } Index: lldb/source/Core/ConstString.cpp =================================================================== --- lldb/source/Core/ConstString.cpp +++ lldb/source/Core/ConstString.cpp @@ -287,7 +287,7 @@ if (s != nullptr) { const char *cstr = AsCString(fail_value); if (cstr != nullptr) - s->PutCString(cstr); + s->PutCString(llvm::StringRef(cstr)); } } Index: lldb/source/Core/Debugger.cpp =================================================================== --- lldb/source/Core/Debugger.cpp +++ lldb/source/Core/Debugger.cpp @@ -280,7 +280,7 @@ std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes( new_prompt, GetUseColor()); if (str.length()) - new_prompt = str.c_str(); + new_prompt = llvm::StringRef(str.c_str()); GetCommandInterpreter().UpdatePrompt(new_prompt); EventSP prompt_change_event_sp( new Event(CommandInterpreter::eBroadcastBitResetPrompt, @@ -339,8 +339,8 @@ llvm::StringRef Debugger::GetPrompt() const { const uint32_t idx = ePropertyPrompt; - return m_collection_sp->GetPropertyAtIndexAsString( - nullptr, idx, g_properties[idx].default_cstr_value); + return llvm::StringRef(m_collection_sp->GetPropertyAtIndexAsString( + nullptr, idx, g_properties[idx].default_cstr_value)); } void Debugger::SetPrompt(llvm::StringRef p) { @@ -350,7 +350,7 @@ std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor()); if (str.length()) - new_prompt = str.c_str(); + new_prompt = llvm::StringRef(str.c_str()); GetCommandInterpreter().UpdatePrompt(new_prompt); } @@ -1429,7 +1429,8 @@ content_stream.Flush(); // Print it. - output_stream_sp->PutCString(content_stream.GetString().c_str()); + output_stream_sp->PutCString( + llvm::StringRef(content_stream.GetString().c_str())); } } else { error_stream_sp->Printf("Failed to print structured " @@ -1542,7 +1543,7 @@ if (data && data[0]) { StreamSP error_sp(GetAsyncErrorStream()); if (error_sp) { - error_sp->PutCString(data); + error_sp->PutCString(llvm::StringRef(data)); error_sp->Flush(); } } @@ -1553,7 +1554,7 @@ if (data && data[0]) { StreamSP output_sp(GetAsyncOutputStream()); if (output_sp) { - output_sp->PutCString(data); + output_sp->PutCString(llvm::StringRef(data)); output_sp->Flush(); } } Index: lldb/source/Core/Disassembler.cpp =================================================================== --- lldb/source/Core/Disassembler.cpp +++ lldb/source/Core/Disassembler.cpp @@ -347,7 +347,7 @@ .GetCString(); if (function_name) { RegularExpression::Match regex_match(1); - if (avoid_regex->Execute(function_name, ®ex_match)) { + if (avoid_regex->Execute(llvm::StringRef(function_name), ®ex_match)) { // skip this source line return true; } @@ -725,15 +725,15 @@ opcode_column_width = m_opcode_name.length() + 1; } - ss.PutCString(m_opcode_name.c_str()); + ss.PutCString(llvm::StringRef(m_opcode_name.c_str())); ss.FillLastLineToColumn(opcode_pos + opcode_column_width, ' '); - ss.PutCString(m_mnemonics.c_str()); + ss.PutCString(llvm::StringRef(m_mnemonics.c_str())); if (!m_comment.empty()) { ss.FillLastLineToColumn( opcode_pos + opcode_column_width + operand_column_width, ' '); ss.PutCString(" ; "); - ss.PutCString(m_comment.c_str()); + ss.PutCString(llvm::StringRef(m_comment.c_str())); } s->Write(ss.GetData(), ss.GetSize()); } Index: lldb/source/Core/DynamicLoader.cpp =================================================================== --- lldb/source/Core/DynamicLoader.cpp +++ lldb/source/Core/DynamicLoader.cpp @@ -191,7 +191,7 @@ if (error.Success() && memory_info.GetMapped() && memory_info.GetRange().GetRangeBase() == base_addr) { ModuleSpec new_module_spec( - FileSpec(memory_info.GetName().AsCString(), false), + FileSpec(llvm::StringRef(memory_info.GetName().AsCString()), false), target.GetArchitecture()); if ((module_sp = modules.FindFirstModule(new_module_spec))) { Index: lldb/source/Core/FileSpecList.cpp =================================================================== --- lldb/source/Core/FileSpecList.cpp +++ lldb/source/Core/FileSpecList.cpp @@ -71,7 +71,7 @@ for (pos = m_files.begin(); pos != end; ++pos) { pos->Dump(s); if (separator_cstr && ((pos + 1) != end)) - s->PutCString(separator_cstr); + s->PutCString(llvm::StringRef(separator_cstr)); } } Index: lldb/source/Core/FormatEntity.cpp =================================================================== --- lldb/source/Core/FormatEntity.cpp +++ lldb/source/Core/FormatEntity.cpp @@ -1106,7 +1106,7 @@ return true; // Only return true if all items succeeded case Entry::Type::String: - s.PutCString(entry.string.c_str()); + s.PutCString(llvm::StringRef(entry.string.c_str())); return true; case Entry::Type::Scope: { @@ -1236,7 +1236,7 @@ if (thread) { const char *cstr = thread->GetName(); if (cstr && cstr[0]) { - s.PutCString(cstr); + s.PutCString(llvm::StringRef(cstr)); return true; } } @@ -1249,7 +1249,7 @@ if (thread) { const char *cstr = thread->GetQueueName(); if (cstr && cstr[0]) { - s.PutCString(cstr); + s.PutCString(llvm::StringRef(cstr)); return true; } } @@ -1264,7 +1264,7 @@ if (stop_info_sp && stop_info_sp->IsValid()) { const char *cstr = stop_info_sp->GetDescription(); if (cstr && cstr[0]) { - s.PutCString(cstr); + s.PutCString(llvm::StringRef(cstr)); return true; } } @@ -1335,7 +1335,7 @@ if (target) { const ArchSpec &arch = target->GetArchitecture(); if (arch.IsValid()) { - s.PutCString(arch.GetArchitectureName()); + s.PutCString(llvm::StringRef(arch.GetArchitectureName())); return true; } } @@ -1379,7 +1379,7 @@ const char *lang_name = Language::GetNameForLanguageType(cu->GetLanguage()); if (lang_name) { - s.PutCString(lang_name); + s.PutCString(llvm::StringRef(lang_name)); return true; } } @@ -1496,7 +1496,7 @@ sc, exe_ctx, Language::FunctionNameRepresentation::eName, ss); } if (language_plugin_handled) { - s.PutCString(ss.GetData()); + s.PutCString(llvm::StringRef(ss.GetData())); return true; } else { const char *name = nullptr; @@ -1505,7 +1505,7 @@ else if (sc->symbol) name = sc->symbol->GetName().AsCString(nullptr); if (name) { - s.PutCString(name); + s.PutCString(llvm::StringRef(name)); if (sc->block) { Block *inline_block = sc->block->GetContainingInlinedBlock(); @@ -1538,7 +1538,7 @@ ss); } if (language_plugin_handled) { - s.PutCString(ss.GetData()); + s.PutCString(llvm::StringRef(ss.GetData())); return true; } else { ConstString name; @@ -1547,7 +1547,7 @@ else if (sc->symbol) name = sc->symbol->GetNameNoArguments(); if (name) { - s.PutCString(name.GetCString()); + s.PutCString(llvm::StringRef(name.GetCString())); return true; } } @@ -1567,7 +1567,7 @@ sc, exe_ctx, Language::FunctionNameRepresentation::eNameWithArgs, ss); } if (language_plugin_handled) { - s.PutCString(ss.GetData()); + s.PutCString(llvm::StringRef(ss.GetData())); return true; } else { // Print the function name with arguments in it @@ -1596,7 +1596,7 @@ } if (inline_info) { - s.PutCString(cstr); + s.PutCString(llvm::StringRef(cstr)); s.PutCString(" [inlined] "); cstr = inline_info->GetName(sc->function->GetLanguage()).GetCString(); @@ -1640,7 +1640,7 @@ if (open_paren) s.Write(cstr, open_paren - cstr + 1); else { - s.PutCString(cstr); + s.PutCString(llvm::StringRef(cstr)); s.PutChar('('); } const size_t num_args = args.GetSize(); @@ -1697,19 +1697,19 @@ } if (close_paren) - s.PutCString(close_paren); + s.PutCString(llvm::StringRef(close_paren)); else s.PutChar(')'); } else { - s.PutCString(cstr); + s.PutCString(llvm::StringRef(cstr)); } return true; } } else if (sc->symbol) { const char *cstr = sc->symbol->GetName().AsCString(nullptr); if (cstr) { - s.PutCString(cstr); + s.PutCString(llvm::StringRef(cstr)); return true; } } @@ -1846,7 +1846,8 @@ const size_t n = parent->num_children; for (size_t i = 0; i < n; ++i) { const FormatEntity::Entry::Definition *entry_def = parent->children + i; - if (key.equals(entry_def->name) || entry_def->name[0] == '*') { + if (key.equals(llvm::StringRef(entry_def->name)) || + entry_def->name[0] == '*') { llvm::StringRef value; if (sep_char) value = @@ -1930,7 +1931,8 @@ const size_t n = parent->num_children; for (size_t i = 0; i < n; ++i) { const FormatEntity::Entry::Definition *entry_def = parent->children + i; - if (p.first.equals(entry_def->name) || entry_def->name[0] == '*') { + if (p.first.equals(llvm::StringRef(entry_def->name)) || + entry_def->name[0] == '*') { if (p.second.empty()) { if (format_str.back() == '.') remainder = format_str.drop_front(format_str.size() - 1); @@ -2284,10 +2286,10 @@ file_spec.Dump(&s); return true; } else if (variable_name.equals(".basename")) { - s.PutCString(file_spec.GetFilename().AsCString("")); + s.PutCString(llvm::StringRef(file_spec.GetFilename().AsCString(""))); return true; } else if (variable_name.equals(".dirname")) { - s.PutCString(file_spec.GetFilename().AsCString("")); + s.PutCString(llvm::StringRef(file_spec.GetFilename().AsCString(""))); return true; } return false; Index: lldb/source/Core/IOHandler.cpp =================================================================== --- lldb/source/Core/IOHandler.cpp +++ lldb/source/Core/IOHandler.cpp @@ -139,7 +139,7 @@ 0, *this), m_default_response(default_response), m_user_response(default_response) { StreamString prompt_stream; - prompt_stream.PutCString(prompt); + prompt_stream.PutCString(llvm::StringRef(prompt)); if (m_default_response) prompt_stream.Printf(": [Y/n] "); else Index: lldb/source/Core/Log.cpp =================================================================== --- lldb/source/Core/Log.cpp +++ lldb/source/Core/Log.cpp @@ -106,16 +106,16 @@ llvm::raw_string_ostream stream(back_trace); llvm::sys::PrintStackTrace(stream); stream.flush(); - header.PutCString(back_trace.c_str()); + header.PutCString(llvm::StringRef(back_trace.c_str())); } if (m_options.Test(LLDB_LOG_OPTION_THREADSAFE)) { static std::recursive_mutex g_LogThreadedMutex; std::lock_guard guard(g_LogThreadedMutex); - stream_sp->PutCString(header.GetString().c_str()); + stream_sp->PutCString(llvm::StringRef(header.GetString().c_str())); stream_sp->Flush(); } else { - stream_sp->PutCString(header.GetString().c_str()); + stream_sp->PutCString(llvm::StringRef(header.GetString().c_str())); stream_sp->Flush(); } } Index: lldb/source/Core/Mangled.cpp =================================================================== --- lldb/source/Core/Mangled.cpp +++ lldb/source/Core/Mangled.cpp @@ -329,11 +329,11 @@ bool Mangled::NameMatches(const RegularExpression ®ex, lldb::LanguageType language) const { - if (m_mangled && regex.Execute(m_mangled.AsCString())) + if (m_mangled && regex.Execute(llvm::StringRef(m_mangled.AsCString()))) return true; ConstString demangled = GetDemangledName(language); - if (demangled && regex.Execute(demangled.AsCString())) + if (demangled && regex.Execute(llvm::StringRef(demangled.AsCString()))) return true; return false; } Index: lldb/source/Core/Module.cpp =================================================================== --- lldb/source/Core/Module.cpp +++ lldb/source/Core/Module.cpp @@ -593,7 +593,7 @@ bool check_inlines, uint32_t resolve_scope, SymbolContextList &sc_list) { - FileSpec file_spec(file_path, false); + FileSpec file_spec(llvm::StringRef(file_path), false); return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines, resolve_scope, sc_list); } @@ -1103,7 +1103,7 @@ if (level == eDescriptionLevelBrief) { const char *filename = m_file.GetFilename().GetCString(); if (filename) - s->PutCString(filename); + s->PutCString(llvm::StringRef(filename)); } else { char path[PATH_MAX]; if (m_file.GetPath(path, sizeof(path))) @@ -1219,7 +1219,7 @@ std::string back_trace; llvm::raw_string_ostream stream(back_trace); llvm::sys::PrintStackTrace(stream); - log_message.PutCString(back_trace.c_str()); + log_message.PutCString(llvm::StringRef(back_trace.c_str())); } log->PutCString(log_message.GetString().c_str()); } Index: lldb/source/Core/ModuleList.cpp =================================================================== --- lldb/source/Core/ModuleList.cpp +++ lldb/source/Core/ModuleList.cpp @@ -609,7 +609,7 @@ uint32_t ModuleList::ResolveSymbolContextForFilePath( const char *file_path, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList &sc_list) const { - FileSpec file_spec(file_path, false); + FileSpec file_spec(llvm::StringRef(file_path), false); return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines, resolve_scope, sc_list); } @@ -766,7 +766,7 @@ if (!search_path_spec.Exists() || !search_path_spec.IsDirectory()) continue; search_path_spec.AppendPathComponent( - module_spec.GetFileSpec().GetFilename().AsCString()); + llvm::StringRef(module_spec.GetFileSpec().GetFilename().AsCString())); if (!search_path_spec.Exists()) continue; Index: lldb/source/Core/Scalar.cpp =================================================================== --- lldb/source/Core/Scalar.cpp +++ lldb/source/Core/Scalar.cpp @@ -289,14 +289,14 @@ case e_slonglong: case e_sint128: case e_sint256: - s->PutCString(m_integer.toString(10, true).c_str()); + s->PutCString(llvm::StringRef(m_integer.toString(10, true).c_str())); break; case e_uint: case e_ulong: case e_ulonglong: case e_uint128: case e_uint256: - s->PutCString(m_integer.toString(10, false).c_str()); + s->PutCString(llvm::StringRef(m_integer.toString(10, false).c_str())); break; case e_float: case e_double: Index: lldb/source/Core/SearchFilter.cpp =================================================================== --- lldb/source/Core/SearchFilter.cpp +++ lldb/source/Core/SearchFilter.cpp @@ -71,7 +71,7 @@ std::string subclass_name; bool success = filter_dict.GetValueForKeyAsString( - GetSerializationSubclassKey(), subclass_name); + llvm::StringRef(GetSerializationSubclassKey()), subclass_name); if (!success) { error.SetErrorStringWithFormat("Filter data missing subclass key"); return result_sp; @@ -86,7 +86,7 @@ StructuredData::Dictionary *subclass_options = nullptr; success = filter_dict.GetValueForKeyAsDictionary( - GetSerializationSubclassOptionsKey(), subclass_options); + llvm::StringRef(GetSerializationSubclassOptionsKey()), subclass_options); if (!success || !subclass_options || !subclass_options->IsValid()) { error.SetErrorString("Filter data missing subclass options key."); return result_sp; @@ -154,8 +154,10 @@ return StructuredData::DictionarySP(); StructuredData::DictionarySP type_dict_sp(new StructuredData::Dictionary()); - type_dict_sp->AddStringItem(GetSerializationSubclassKey(), GetFilterName()); - type_dict_sp->AddItem(GetSerializationSubclassOptionsKey(), options_dict_sp); + type_dict_sp->AddStringItem(llvm::StringRef(GetSerializationSubclassKey()), + GetFilterName()); + type_dict_sp->AddItem(llvm::StringRef(GetSerializationSubclassOptionsKey()), + options_dict_sp); return type_dict_sp; } @@ -174,7 +176,7 @@ module_array_sp->AddItem(StructuredData::StringSP( new StructuredData::String(file_list.GetFileSpecAtIndex(i).GetPath()))); } - options_dict_sp->AddItem(GetKey(name), module_array_sp); + options_dict_sp->AddItem(llvm::StringRef(GetKey(name)), module_array_sp); } //---------------------------------------------------------------------- @@ -438,7 +440,8 @@ m_module_spec.GetPath(buffer, 2047); s->PutCString(buffer); } else { - s->PutCString(m_module_spec.GetFilename().AsCString("")); + s->PutCString( + llvm::StringRef(m_module_spec.GetFilename().AsCString(""))); } } @@ -457,8 +460,8 @@ SearchFilterSP SearchFilterByModule::CreateFromStructuredData( Target &target, const StructuredData::Dictionary &data_dict, Error &error) { StructuredData::Array *modules_array; - bool success = data_dict.GetValueForKeyAsArray(GetKey(OptionNames::ModList), - modules_array); + bool success = data_dict.GetValueForKeyAsArray( + llvm::StringRef(GetKey(OptionNames::ModList)), modules_array); if (!success) { error.SetErrorString("SFBM::CFSD: Could not find the module list key."); return nullptr; @@ -477,7 +480,7 @@ error.SetErrorString("SFBM::CFSD: filter module item not a string."); return nullptr; } - FileSpec module_spec(module.c_str(), false); + FileSpec module_spec(llvm::StringRef(module.c_str()), false); return SearchFilterSP( new SearchFilterByModule(target.shared_from_this(), module_spec)); @@ -489,7 +492,8 @@ StructuredData::ArraySP module_array_sp(new StructuredData::Array()); module_array_sp->AddItem(StructuredData::StringSP( new StructuredData::String(m_module_spec.GetPath()))); - options_dict_sp->AddItem(GetKey(OptionNames::ModList), module_array_sp); + options_dict_sp->AddItem(llvm::StringRef(GetKey(OptionNames::ModList)), + module_array_sp); return WrapOptionsDict(options_dict_sp); } @@ -596,9 +600,9 @@ m_module_spec_list.GetFileSpecAtIndex(0).GetPath(buffer, 2047); s->PutCString(buffer); } else { - s->PutCString( + s->PutCString(llvm::StringRef( m_module_spec_list.GetFileSpecAtIndex(0).GetFilename().AsCString( - "")); + ""))); } } else { s->Printf(", modules(%" PRIu64 ") = ", (uint64_t)num_modules); @@ -608,9 +612,9 @@ m_module_spec_list.GetFileSpecAtIndex(i).GetPath(buffer, 2047); s->PutCString(buffer); } else { - s->PutCString( + s->PutCString(llvm::StringRef( m_module_spec_list.GetFileSpecAtIndex(i).GetFilename().AsCString( - "")); + ""))); } if (i != num_modules - 1) s->PutCString(", "); @@ -633,8 +637,8 @@ SearchFilterSP SearchFilterByModuleList::CreateFromStructuredData( Target &target, const StructuredData::Dictionary &data_dict, Error &error) { StructuredData::Array *modules_array; - bool success = data_dict.GetValueForKeyAsArray(GetKey(OptionNames::ModList), - modules_array); + bool success = data_dict.GetValueForKeyAsArray( + llvm::StringRef(GetKey(OptionNames::ModList)), modules_array); FileSpecList modules; if (success) { size_t num_modules = modules_array->GetSize(); @@ -646,7 +650,7 @@ "SFBM::CFSD: filter module item %zu not a string.", i); return nullptr; } - modules.Append(FileSpec(module.c_str(), false)); + modules.Append(FileSpec(llvm::StringRef(module.c_str()), false)); } } @@ -698,8 +702,8 @@ Target &target, const StructuredData::Dictionary &data_dict, Error &error) { StructuredData::Array *modules_array = nullptr; SearchFilterSP result_sp; - bool success = data_dict.GetValueForKeyAsArray(GetKey(OptionNames::ModList), - modules_array); + bool success = data_dict.GetValueForKeyAsArray( + llvm::StringRef(GetKey(OptionNames::ModList)), modules_array); FileSpecList modules; if (success) { size_t num_modules = modules_array->GetSize(); @@ -711,13 +715,13 @@ "SFBM::CFSD: filter module item %zu not a string.", i); return result_sp; } - modules.Append(FileSpec(module.c_str(), false)); + modules.Append(FileSpec(llvm::StringRef(module.c_str()), false)); } } StructuredData::Array *cus_array = nullptr; - success = - data_dict.GetValueForKeyAsArray(GetKey(OptionNames::CUList), cus_array); + success = data_dict.GetValueForKeyAsArray( + llvm::StringRef(GetKey(OptionNames::CUList)), cus_array); if (!success) { error.SetErrorString("SFBM::CFSD: Could not find the CU list key."); return result_sp; @@ -733,7 +737,7 @@ "SFBM::CFSD: filter cu item %zu not a string.", i); return nullptr; } - cus.Append(FileSpec(cu.c_str(), false)); + cus.Append(FileSpec(llvm::StringRef(cu.c_str()), false)); } return SearchFilterSP(new SearchFilterByModuleListAndCU( @@ -832,9 +836,9 @@ m_module_spec_list.GetFileSpecAtIndex(0).GetPath(buffer, 2047); s->PutCString(buffer); } else { - s->PutCString( + s->PutCString(llvm::StringRef( m_module_spec_list.GetFileSpecAtIndex(0).GetFilename().AsCString( - "")); + ""))); } } else if (num_modules > 0) { s->Printf(", modules(%" PRIu64 ") = ", static_cast(num_modules)); @@ -844,9 +848,9 @@ m_module_spec_list.GetFileSpecAtIndex(i).GetPath(buffer, 2047); s->PutCString(buffer); } else { - s->PutCString( + s->PutCString(llvm::StringRef( m_module_spec_list.GetFileSpecAtIndex(i).GetFilename().AsCString( - "")); + ""))); } if (i != num_modules - 1) s->PutCString(", "); Index: lldb/source/Core/Stream.cpp =================================================================== --- lldb/source/Core/Stream.cpp +++ lldb/source/Core/Stream.cpp @@ -138,11 +138,11 @@ uint32_t addr_size, const char *prefix, const char *suffix) { if (prefix && prefix[0]) - PutCString(prefix); + PutCString(llvm::StringRef(prefix)); Address(lo_addr, addr_size, "["); Address(hi_addr, addr_size, "-", ")"); if (suffix && suffix[0]) - PutCString(suffix); + PutCString(llvm::StringRef(suffix)); } size_t Stream::PutChar(char ch) { return Write(&ch, 1); } @@ -605,7 +605,7 @@ const char *hola = "Hello World!!!"; s->PutChar(' '); - s->PutCString(hola); + s->PutCString(llvm::StringRef(hola)); s->PutChar(' '); s->Write(hola, 5); Index: lldb/source/Core/StringList.cpp =================================================================== --- lldb/source/Core/StringList.cpp +++ lldb/source/Core/StringList.cpp @@ -95,8 +95,8 @@ for (uint32_t i = 0; i < size; ++i) { if (i > 0) - strm.PutCString(separator); - strm.PutCString(GetStringAtIndex(i)); + strm.PutCString(llvm::StringRef(separator)); + strm.PutCString(llvm::StringRef(GetStringAtIndex(i))); } } Index: lldb/source/Core/StructuredData.cpp =================================================================== --- lldb/source/Core/StructuredData.cpp +++ lldb/source/Core/StructuredData.cpp @@ -181,7 +181,8 @@ if (this->GetType() == Type::eTypeDictionary) { std::pair match = path.split('.'); std::string key = match.first.str(); - ObjectSP value = this->GetAsDictionary()->GetValueForKey(key.c_str()); + ObjectSP value = + this->GetAsDictionary()->GetValueForKey(llvm::StringRef(key.c_str())); if (value.get()) { // Do we have additional words to descend? If not, return the // value we're at right now. Index: lldb/source/Core/ValueObject.cpp =================================================================== --- lldb/source/Core/ValueObject.cpp +++ lldb/source/Core/ValueObject.cpp @@ -1478,7 +1478,7 @@ } if (cstr) - s.PutCString(cstr); + s.PutCString(llvm::StringRef(cstr)); else { if (m_error.Fail()) { if (do_dump_error) @@ -2034,7 +2034,7 @@ if (this_had_base_class) { if (parent_had_base_class) s.PutCString("::"); - s.PutCString(cxx_class_name.c_str()); + s.PutCString(llvm::StringRef(cxx_class_name.c_str())); } return parent_had_base_class || this_had_base_class; } @@ -2124,7 +2124,7 @@ // printing, then add our name ([%d]) to the expression path if (m_is_array_item_for_pointer && epformat == eGetExpressionPathFormatHonorPointers) - s.PutCString(m_name.AsCString()); + s.PutCString(llvm::StringRef(m_name.AsCString())); if (!IsBaseClass()) { if (!is_deref_of_parent) { @@ -2157,7 +2157,7 @@ if (GetBaseClassPath(s)) s.PutCString("::"); } - s.PutCString(name); + s.PutCString(llvm::StringRef(name)); } } } Index: lldb/source/DataFormatters/TypeSummary.cpp =================================================================== --- lldb/source/DataFormatters/TypeSummary.cpp +++ lldb/source/DataFormatters/TypeSummary.cpp @@ -74,7 +74,7 @@ m_format.Clear(); if (format_cstr && format_cstr[0]) { m_format_str = format_cstr; - m_error = FormatEntity::Parse(format_cstr, m_format); + m_error = FormatEntity::Parse(llvm::StringRef(format_cstr), m_format); } else { m_format_str.clear(); m_error.Clear(); @@ -207,10 +207,10 @@ if (m_function_name.empty()) { sstr.PutCString("no backing script"); } else { - sstr.PutCString(m_function_name.c_str()); + sstr.PutCString(llvm::StringRef(m_function_name.c_str())); } } else { - sstr.PutCString(m_python_script.c_str()); + sstr.PutCString(llvm::StringRef(m_python_script.c_str())); } return sstr.GetString(); } Index: lldb/source/DataFormatters/ValueObjectPrinter.cpp =================================================================== --- lldb/source/DataFormatters/ValueObjectPrinter.cpp +++ lldb/source/DataFormatters/ValueObjectPrinter.cpp @@ -575,7 +575,7 @@ m_stream->EOL(); } else { if (ShouldPrintValueObject()) - m_stream->PutCString(IsRef() ? ": {\n" : " {\n"); + m_stream->PutCString(llvm::StringRef(IsRef() ? ": {\n" : " {\n")); m_stream->IndentMore(); } } @@ -746,7 +746,7 @@ if (!hide_names) { const char *name = child_sp.get()->GetName().AsCString(); if (name && *name) { - m_stream->PutCString(name); + m_stream->PutCString(llvm::StringRef(name)); m_stream->PutCString(" = "); } } Index: lldb/source/Expression/DWARFExpression.cpp =================================================================== --- lldb/source/Expression/DWARFExpression.cpp +++ lldb/source/Expression/DWARFExpression.cpp @@ -370,10 +370,10 @@ RegisterInfo reg_info; if (abi->GetRegisterInfoByKind(m_reg_kind, reg_num, reg_info)) { if (reg_info.name) { - s->PutCString(reg_info.name); + s->PutCString(llvm::StringRef(reg_info.name)); break; } else if (reg_info.alt_name) { - s->PutCString(reg_info.alt_name); + s->PutCString(llvm::StringRef(reg_info.alt_name)); break; } } @@ -438,10 +438,10 @@ RegisterInfo reg_info; if (abi->GetRegisterInfoByKind(m_reg_kind, reg_num, reg_info)) { if (reg_info.name) { - s->PutCString(reg_info.name); + s->PutCString(llvm::StringRef(reg_info.name)); break; } else if (reg_info.alt_name) { - s->PutCString(reg_info.alt_name); + s->PutCString(llvm::StringRef(reg_info.alt_name)); break; } } Index: lldb/source/Expression/IRExecutionUnit.cpp =================================================================== --- lldb/source/Expression/IRExecutionUnit.cpp +++ lldb/source/Expression/IRExecutionUnit.cpp @@ -420,9 +420,10 @@ ss.PutCString("\n"); emitNewLine = true; ss.PutCString(" "); - ss.PutCString(Mangled(failed_lookup) - .GetDemangledName(lldb::eLanguageTypeObjC_plus_plus) - .AsCString()); + ss.PutCString(llvm::StringRef( + Mangled(failed_lookup) + .GetDemangledName(lldb::eLanguageTypeObjC_plus_plus) + .AsCString())); } m_failed_lookups.clear(); Index: lldb/source/Expression/REPL.cpp =================================================================== --- lldb/source/Expression/REPL.cpp +++ lldb/source/Expression/REPL.cpp @@ -69,7 +69,8 @@ m_repl_source_path = tmpdir_file_spec.GetPath(); } else { tmpdir_file_spec = FileSpec("/tmp", false); - tmpdir_file_spec.AppendPathComponent(file_basename.AsCString()); + tmpdir_file_spec.AppendPathComponent( + llvm::StringRef(file_basename.AsCString())); } return tmpdir_file_spec.GetPath(); @@ -433,7 +434,8 @@ // Now set the default file and line to the REPL source file m_target.GetSourceManager().SetDefaultFileAndLine( - FileSpec(m_repl_source_path.c_str(), false), new_default_line); + FileSpec(llvm::StringRef(m_repl_source_path.c_str()), false), + new_default_line); } static_cast(io_handler) .SetBaseLineNumber(m_code.GetSize() + 1); Index: lldb/source/Host/common/FileSpec.cpp =================================================================== --- lldb/source/Host/common/FileSpec.cpp +++ lldb/source/Host/common/FileSpec.cpp @@ -102,7 +102,8 @@ if (str.size() > 0 && IsPathSeparator(str.back(), syntax)) return str.size() - 1; - size_t pos = str.find_last_of(GetPathSeparators(syntax), str.size() - 1); + size_t pos = str.find_last_of(llvm::StringRef(GetPathSeparators(syntax)), + str.size() - 1); if (!PathSyntaxIsPosix(syntax) && pos == llvm::StringRef::npos) pos = str.find_last_of(':', str.size() - 2); @@ -127,7 +128,7 @@ // case "//net" if (str.size() > 3 && IsPathSeparator(str[0], syntax) && str[0] == str[1] && !IsPathSeparator(str[2], syntax)) - return str.find_first_of(GetPathSeparators(syntax), 2); + return str.find_first_of(llvm::StringRef(GetPathSeparators(syntax)), 2); // case "/" if (str.size() > 0 && IsPathSeparator(str[0], syntax)) @@ -591,10 +592,10 @@ llvm::StringRef backup_sep; if (is_win) { found_sep = win_sep; - backup_sep = win_backup; + backup_sep = llvm::StringRef(win_backup); } else { found_sep = unix_sep; - backup_sep = unix_backup; + backup_sep = llvm::StringRef(unix_backup); } llvm::StringRef input_ref(input); @@ -657,7 +658,7 @@ void FileSpec::Dump(Stream *s) const { if (s) { std::string path{GetPath(true)}; - s->PutCString(path.c_str()); + s->PutCString(llvm::StringRef(path.c_str())); char path_separator = GetPreferredPathSeparator(m_syntax); if (!m_filename && !path.empty() && path.back() != path_separator) s->PutChar(path_separator); @@ -703,7 +704,7 @@ // If FindProgramByName found the file, it returns the directory + // filename in its return results. // We need to separate them. - FileSpec tmp_file(dir_ref.data(), false); + FileSpec tmp_file(llvm::StringRef(dir_ref.data()), false); if (tmp_file.Exists()) { m_directory = tmp_file.m_directory; return true; @@ -1267,9 +1268,9 @@ size_t last_slash_pos = last_slash_ptr - dir_cstr + 1; ConstString new_path(dir_cstr, last_slash_pos); - return FileSpec(new_path.GetCString(), resolve); + return FileSpec(llvm::StringRef(new_path.GetCString()), resolve); } else - return FileSpec(m_directory.GetCString(), resolve); + return FileSpec(llvm::StringRef(m_directory.GetCString()), resolve); } ConstString FileSpec::GetLastPathComponent() const { @@ -1387,9 +1388,9 @@ } size_t last_slash_pos = last_slash_ptr - dir_cstr + 1; ConstString new_path(dir_cstr, last_slash_pos); - SetFile(new_path.GetCString(), resolve); + SetFile(llvm::StringRef(new_path.GetCString()), resolve); } else - SetFile(m_directory.GetCString(), resolve); + SetFile(llvm::StringRef(m_directory.GetCString()), resolve); } //------------------------------------------------------------------ /// Returns true if the filespec represents an implementation source Index: lldb/source/Host/common/Host.cpp =================================================================== --- lldb/source/Host/common/Host.cpp +++ lldb/source/Host/common/Host.cpp @@ -458,7 +458,7 @@ Dl_info info; if (::dladdr(host_addr, &info)) { if (info.dli_fname) - module_filespec.SetFile(info.dli_fname, true); + module_filespec.SetFile(llvm::StringRef(info.dli_fname), true); } #endif return module_filespec; @@ -502,8 +502,9 @@ int *status_ptr, int *signo_ptr, std::string *command_output_ptr, uint32_t timeout_sec, bool run_in_default_shell) { - return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr, - command_output_ptr, timeout_sec, run_in_default_shell); + return RunShellCommand(Args(llvm::StringRef(command)), working_dir, + status_ptr, signo_ptr, command_output_ptr, timeout_sec, + run_in_default_shell); } Error Host::RunShellCommand(const Args &args, const FileSpec &working_dir, @@ -547,7 +548,7 @@ } } - FileSpec output_file_spec{output_file_path.c_str(), false}; + FileSpec output_file_spec{llvm::StringRef(output_file_path.c_str()), false}; launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false); if (output_file_spec) { Index: lldb/source/Host/common/HostNativeThreadBase.cpp =================================================================== --- lldb/source/Host/common/HostNativeThreadBase.cpp +++ lldb/source/Host/common/HostNativeThreadBase.cpp @@ -52,7 +52,7 @@ HostNativeThreadBase::ThreadCreateTrampoline(lldb::thread_arg_t arg) { ThreadLauncher::HostThreadCreateInfo *info = (ThreadLauncher::HostThreadCreateInfo *)arg; - ThisThread::SetName(info->thread_name.c_str(), + ThisThread::SetName(llvm::StringRef(info->thread_name.c_str()), HostInfo::GetMaxThreadNameLength()); thread_func_t thread_fptr = info->thread_fptr; Index: lldb/source/Host/common/Symbols.cpp =================================================================== --- lldb/source/Host/common/Symbols.cpp +++ lldb/source/Host/common/Symbols.cpp @@ -204,7 +204,7 @@ // Add module directory. const ConstString &file_dir = module_spec.GetFileSpec().GetDirectory(); debug_file_search_paths.AppendIfUnique( - FileSpec(file_dir.AsCString("."), true)); + FileSpec(llvm::StringRef(file_dir.AsCString(".")), true)); // Add current working directory. debug_file_search_paths.AppendIfUnique(FileSpec(".", true)); @@ -246,7 +246,7 @@ const uint32_t num_files = files.size(); for (size_t idx_file = 0; idx_file < num_files; ++idx_file) { const std::string &filename = files[idx_file]; - FileSpec file_spec(filename.c_str(), true); + FileSpec file_spec(llvm::StringRef(filename.c_str()), true); if (llvm::sys::fs::equivalent(file_spec.GetPath(), module_spec.GetFileSpec().GetPath())) Index: lldb/source/Host/common/ThisThread.cpp =================================================================== --- lldb/source/Host/common/ThisThread.cpp +++ lldb/source/Host/common/ThisThread.cpp @@ -46,5 +46,5 @@ truncated_name = truncated_name.substr(begin, count); } - SetName(truncated_name.c_str()); + SetName(llvm::StringRef(truncated_name.c_str())); } Index: lldb/source/Host/common/TimeValue.cpp =================================================================== --- lldb/source/Host/common/TimeValue.cpp +++ lldb/source/Host/common/TimeValue.cpp @@ -115,7 +115,7 @@ if (width > 0) s->Printf("%-*s", width, time_cstr); else - s->PutCString(time_cstr); + s->PutCString(llvm::StringRef(time_cstr)); } else if (width > 0) s->Printf("%-*s", width, ""); #endif Index: lldb/source/Host/common/XML.cpp =================================================================== --- lldb/source/Host/common/XML.cpp +++ lldb/source/Host/common/XML.cpp @@ -69,7 +69,7 @@ XMLNode root_node(xmlDocGetRootElement(m_document)); if (required_name) { llvm::StringRef actual_name = root_node.GetName(); - if (actual_name == required_name) + if (actual_name == llvm::StringRef(required_name)) return root_node; } else { return root_node; Index: lldb/source/Host/macosx/Host.mm =================================================================== --- lldb/source/Host/macosx/Host.mm +++ lldb/source/Host/macosx/Host.mm @@ -787,7 +787,7 @@ triple_arch == llvm::Triple::x86_64); const char *cstr = data.GetCStr(&offset); if (cstr) { - process_info.GetExecutableFile().SetFile(cstr, false); + process_info.GetExecutableFile().SetFile(llvm::StringRef(cstr), false); if (match_info_ptr == NULL || NameMatches( @@ -1319,7 +1319,7 @@ expand_tool_spec_stream.Printf("\"%s\"", expand_tool_spec.GetPath().c_str()); - Args expand_command(expand_tool_spec_stream.GetData()); + Args expand_command(llvm::StringRef(expand_tool_spec_stream.GetData())); expand_command.AppendArguments(launch_info.GetArguments()); int status; @@ -1332,7 +1332,7 @@ "cwd does not exist; cannot launch with shell argument expansion"); return error; } else { - FileSpec working_dir(wd, false); + FileSpec working_dir(llvm::StringRef(wd), false); free(wd); launch_info.SetWorkingDirectory(working_dir); } Index: lldb/source/Host/macosx/HostInfoMacOSX.mm =================================================================== --- lldb/source/Host/macosx/HostInfoMacOSX.mm +++ lldb/source/Host/macosx/HostInfoMacOSX.mm @@ -116,7 +116,8 @@ err = _NSGetExecutablePath(large_program_fullpath, &len); if (err == 0) - g_program_filespec.SetFile(large_program_fullpath, false); + g_program_filespec.SetFile(llvm::StringRef(large_program_fullpath), + false); ::free(large_program_fullpath); } @@ -238,7 +239,7 @@ raw_path.resize(framework_pos); raw_path.append("/Resources/Clang"); } - file_spec.SetFile(raw_path.c_str(), true); + file_spec.SetFile(llvm::StringRef(raw_path.c_str()), true); return true; } Index: lldb/source/Host/macosx/Symbols.cpp =================================================================== --- lldb/source/Host/macosx/Symbols.cpp +++ lldb/source/Host/macosx/Symbols.cpp @@ -294,7 +294,7 @@ (CFDictionaryRef)uuid_dict, CFSTR("DBGSymbolRichExecutable")); if (cf_str && CFGetTypeID(cf_str) == CFStringGetTypeID()) { if (CFCString::FileSystemRepresentation(cf_str, str)) { - module_spec.GetFileSpec().SetFile(str.c_str(), true); + module_spec.GetFileSpec().SetFile(llvm::StringRef(str.c_str()), true); if (log) { log->Printf( "From dsymForUUID plist: Symbol rich executable is at '%s'", @@ -307,7 +307,8 @@ CFSTR("DBGDSYMPath")); if (cf_str && CFGetTypeID(cf_str) == CFStringGetTypeID()) { if (CFCString::FileSystemRepresentation(cf_str, str)) { - module_spec.GetSymbolFileSpec().SetFile(str.c_str(), true); + module_spec.GetSymbolFileSpec().SetFile(llvm::StringRef(str.c_str()), + true); success = true; if (log) { log->Printf("From dsymForUUID plist: dSYM is at '%s'", str.c_str()); @@ -339,7 +340,8 @@ if (!DBGBuildSourcePath.empty() && !DBGSourcePath.empty()) { if (DBGSourcePath[0] == '~') { - FileSpec resolved_source_path(DBGSourcePath.c_str(), true); + FileSpec resolved_source_path(llvm::StringRef(DBGSourcePath.c_str()), + true); DBGSourcePath = resolved_source_path.GetPath(); } module_spec.GetSourceMappingList().Append( @@ -391,7 +393,8 @@ DBGSourcePath = original_DBGSourcePath_value; } if (DBGSourcePath[0] == '~') { - FileSpec resolved_source_path(DBGSourcePath.c_str(), true); + FileSpec resolved_source_path( + llvm::StringRef(DBGSourcePath.c_str()), true); DBGSourcePath = resolved_source_path.GetPath(); } module_spec.GetSourceMappingList().Append( @@ -455,7 +458,8 @@ getenv("LLDB_APPLE_DSYMFORUUID_EXECUTABLE"); FileSpec dsym_for_uuid_exe_spec; if (dsym_for_uuid_exe_path_cstr) { - dsym_for_uuid_exe_spec.SetFile(dsym_for_uuid_exe_path_cstr, true); + dsym_for_uuid_exe_spec.SetFile( + llvm::StringRef(dsym_for_uuid_exe_path_cstr), true); g_dsym_for_uuid_exe_exists = dsym_for_uuid_exe_spec.Exists(); } @@ -474,14 +478,16 @@ tilde_rc && tilde_rc->pw_dir) { std::string dsymforuuid_path(tilde_rc->pw_dir); dsymforuuid_path += "/bin/dsymForUUID"; - dsym_for_uuid_exe_spec.SetFile(dsymforuuid_path.c_str(), false); + dsym_for_uuid_exe_spec.SetFile( + llvm::StringRef(dsymforuuid_path.c_str()), false); g_dsym_for_uuid_exe_exists = dsym_for_uuid_exe_spec.Exists(); } } } } if (!g_dsym_for_uuid_exe_exists && g_dbgshell_command != NULL) { - dsym_for_uuid_exe_spec.SetFile(g_dbgshell_command, true); + dsym_for_uuid_exe_spec.SetFile(llvm::StringRef(g_dbgshell_command), + true); g_dsym_for_uuid_exe_exists = dsym_for_uuid_exe_spec.Exists(); } Index: lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp =================================================================== --- lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp +++ lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp @@ -658,8 +658,8 @@ ConnectionFileDescriptor::NamedSocketAccept(const char *socket_name, Error *error_ptr) { Socket *socket = nullptr; - Error error = - Socket::UnixDomainAccept(socket_name, m_child_processes_inherit, socket); + Error error = Socket::UnixDomainAccept(llvm::StringRef(socket_name), + m_child_processes_inherit, socket); if (error_ptr) *error_ptr = error; m_write_sp.reset(socket); @@ -675,8 +675,8 @@ ConnectionFileDescriptor::NamedSocketConnect(const char *socket_name, Error *error_ptr) { Socket *socket = nullptr; - Error error = - Socket::UnixDomainConnect(socket_name, m_child_processes_inherit, socket); + Error error = Socket::UnixDomainConnect(llvm::StringRef(socket_name), + m_child_processes_inherit, socket); if (error_ptr) *error_ptr = error; m_write_sp.reset(socket); @@ -692,7 +692,7 @@ ConnectionFileDescriptor::UnixAbstractSocketConnect(const char *socket_name, Error *error_ptr) { Socket *socket = nullptr; - Error error = Socket::UnixAbstractConnect(socket_name, + Error error = Socket::UnixAbstractConnect(llvm::StringRef(socket_name), m_child_processes_inherit, socket); if (error_ptr) *error_ptr = error; @@ -712,8 +712,8 @@ Socket *socket = nullptr; m_waiting_for_accept = true; - Error error = Socket::TcpListen(s, m_child_processes_inherit, socket, - &m_port_predicate); + Error error = Socket::TcpListen(llvm::StringRef(s), m_child_processes_inherit, + socket, &m_port_predicate); if (error_ptr) *error_ptr = error; if (error.Fail()) @@ -723,7 +723,8 @@ listening_socket_up.reset(socket); socket = nullptr; - error = listening_socket_up->Accept(s, m_child_processes_inherit, socket); + error = listening_socket_up->Accept(llvm::StringRef(s), + m_child_processes_inherit, socket); listening_socket_up.reset(); if (error_ptr) *error_ptr = error; @@ -737,7 +738,8 @@ ConnectionStatus ConnectionFileDescriptor::ConnectTCP(const char *s, Error *error_ptr) { Socket *socket = nullptr; - Error error = Socket::TcpConnect(s, m_child_processes_inherit, socket); + Error error = + Socket::TcpConnect(llvm::StringRef(s), m_child_processes_inherit, socket); if (error_ptr) *error_ptr = error; m_write_sp.reset(socket); @@ -753,8 +755,8 @@ Error *error_ptr) { Socket *send_socket = nullptr; Socket *recv_socket = nullptr; - Error error = Socket::UdpConnect(s, m_child_processes_inherit, send_socket, - recv_socket); + Error error = Socket::UdpConnect( + llvm::StringRef(s), m_child_processes_inherit, send_socket, recv_socket); if (error_ptr) *error_ptr = error; m_write_sp.reset(send_socket); Index: lldb/source/Host/posix/FileSystem.cpp =================================================================== --- lldb/source/Host/posix/FileSystem.cpp +++ lldb/source/Host/posix/FileSystem.cpp @@ -49,7 +49,8 @@ case ENOENT: { // Parent directory doesn't exist, so lets make it if we can // Make the parent directory and try again - FileSpec parent_file_spec{file_spec.GetDirectory().GetCString(), false}; + FileSpec parent_file_spec{ + llvm::StringRef(file_spec.GetDirectory().GetCString()), false}; error = MakeDirectory(parent_file_spec, file_permissions); if (error.Fail()) return error; @@ -81,7 +82,7 @@ std::vector sub_directories; FileSpec::ForEachItemInDirectory( - file_spec.GetCString(), + llvm::StringRef(file_spec.GetCString()), [&error, &sub_directories]( FileSpec::FileType file_type, const FileSpec &spec) -> FileSpec::EnumerateDirectoryResult { Index: lldb/source/Host/posix/PipePosix.cpp =================================================================== --- lldb/source/Host/posix/PipePosix.cpp +++ lldb/source/Host/posix/PipePosix.cpp @@ -131,10 +131,10 @@ FileSpec tmpdir_file_spec; tmpdir_file_spec.Clear(); if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec)) { - tmpdir_file_spec.AppendPathComponent(pipe_spec.c_str()); + tmpdir_file_spec.AppendPathComponent(llvm::StringRef(pipe_spec.c_str())); } else { tmpdir_file_spec.AppendPathComponent("/tmp"); - tmpdir_file_spec.AppendPathComponent(pipe_spec.c_str()); + tmpdir_file_spec.AppendPathComponent(llvm::StringRef(pipe_spec.c_str())); } // It's possible that another process creates the target path after we've @@ -231,7 +231,7 @@ } Error PipePosix::Delete(llvm::StringRef name) { - return FileSystem::Unlink(FileSpec{name.data(), true}); + return FileSystem::Unlink(FileSpec{llvm::StringRef(name.data()), true}); } bool PipePosix::CanRead() const { Index: lldb/source/Interpreter/Args.cpp =================================================================== --- lldb/source/Interpreter/Args.cpp +++ lldb/source/Interpreter/Args.cpp @@ -47,7 +47,8 @@ static const char *k_escapable_characters = "\"\\"; while (true) { // Skip over over regular characters and append them. - size_t regular = quoted.find_first_of(k_escapable_characters); + size_t regular = + quoted.find_first_of(llvm::StringRef(k_escapable_characters)); result += quoted.substr(0, regular); quoted = quoted.substr(regular); @@ -256,14 +257,14 @@ m_argv.clear(); static const char *k_space_separators = " \t"; - command = command.ltrim(k_space_separators); + command = command.ltrim(llvm::StringRef(k_space_separators)); std::string arg; char quote; while (!command.empty()) { std::tie(arg, quote, command) = ParseSingleArgument(command); m_entries.emplace_back(arg, quote); m_argv.push_back(m_entries.back().data()); - command = command.ltrim(k_space_separators); + command = command.ltrim(llvm::StringRef(k_space_separators)); } m_argv.push_back(nullptr); } @@ -354,7 +355,7 @@ assert(m_argv.back() == nullptr); m_argv.pop_back(); for (auto arg : llvm::makeArrayRef(argv, argc)) { - m_entries.emplace_back(arg, '\0'); + m_entries.emplace_back(llvm::StringRef(arg), '\0'); m_argv.push_back(m_entries.back().data()); } @@ -419,7 +420,7 @@ ? args[i][0] : '\0'; - m_entries[i] = ArgEntry(args[i], quote); + m_entries[i] = ArgEntry(llvm::StringRef(args[i]), quote); m_argv[i] = m_entries[i].data(); } } @@ -558,7 +559,7 @@ Error *error_ptr) { bool error_set = false; if (s && s[0]) { - llvm::StringRef sref = s; + llvm::StringRef sref = llvm::StringRef(s); char *end = nullptr; lldb::addr_t addr = ::strtoull(s, &end, 0); Index: lldb/source/Interpreter/CommandInterpreter.cpp =================================================================== --- lldb/source/Interpreter/CommandInterpreter.cpp +++ lldb/source/Interpreter/CommandInterpreter.cpp @@ -775,10 +775,12 @@ int CommandInterpreter::GetCommandNamesMatchingPartialString( const char *cmd_str, bool include_aliases, StringList &matches) { - AddNamesMatchingPartialString(m_command_dict, cmd_str, matches); + AddNamesMatchingPartialString(m_command_dict, llvm::StringRef(cmd_str), + matches); if (include_aliases) { - AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches); + AddNamesMatchingPartialString(m_alias_dict, llvm::StringRef(cmd_str), + matches); } return matches.GetSize(); @@ -1169,13 +1171,14 @@ // eventually be invoked by the given command line. CommandObject *cmd_obj = nullptr; - size_t start = command_string.find_first_not_of(k_white_space); + size_t start = + command_string.find_first_not_of(llvm::StringRef(k_white_space)); size_t end = 0; bool done = false; while (!done) { if (start != std::string::npos) { // Get the next word from command_string. - end = command_string.find_first_of(k_white_space, start); + end = command_string.find_first_of(llvm::StringRef(k_white_space), start); if (end == std::string::npos) end = command_string.size(); std::string cmd_word = command_string.substr(start, end - start); @@ -1205,7 +1208,8 @@ end >= command_string.size()) done = true; else - start = command_string.find_first_not_of(k_white_space, end); + start = command_string.find_first_not_of(llvm::StringRef(k_white_space), + end); } else // Unable to find any more words. done = true; @@ -1734,8 +1738,8 @@ } else if (cursor_index == 0) { // The cursor is in the first argument, so just do a lookup in the // dictionary. - CommandObject *cmd_obj = - GetCommandObject(parsed_line.GetArgumentAtIndex(0), &matches); + CommandObject *cmd_obj = GetCommandObject( + llvm::StringRef(parsed_line.GetArgumentAtIndex(0)), &matches); num_command_matches = matches.GetSize(); if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() && @@ -1761,7 +1765,7 @@ // to complete the command. // First see if there is a matching initial command: CommandObject *command_object = - GetCommandObject(parsed_line.GetArgumentAtIndex(0)); + GetCommandObject(llvm::StringRef(parsed_line.GetArgumentAtIndex(0))); if (command_object == nullptr) { return 0; } else { @@ -1933,7 +1937,7 @@ std::string &raw_input_string, CommandReturnObject &result) { OptionArgVectorSP option_arg_vector_sp = - GetAlias(alias_name)->GetOptionArguments(); + GetAlias(llvm::StringRef(alias_name))->GetOptionArguments(); bool wants_raw_input = alias_cmd_obj->WantsRawCommandString(); @@ -2012,7 +2016,8 @@ } if (value_type != OptionParser::eOptionalArgument) - new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index)); + new_args.AppendArgument( + llvm::StringRef(cmd_args.GetArgumentAtIndex(index))); else { char buffer[255]; ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(), @@ -2094,7 +2099,8 @@ FileSpec dot_lldb(".lldbinit", true); llvm::SmallString<64> home_dir_path; llvm::sys::path::home_directory(home_dir_path); - FileSpec homedir_dot_lldb(home_dir_path.c_str(), false); + FileSpec homedir_dot_lldb(llvm::StringRef(home_dir_path.c_str()), + false); homedir_dot_lldb.AppendPathComponent(".lldbinit"); homedir_dot_lldb.ResolvePath(); if (dot_lldb.Exists() && @@ -2127,7 +2133,7 @@ // load the init files. llvm::SmallString<64> home_dir_path; llvm::sys::path::home_directory(home_dir_path); - FileSpec profilePath(home_dir_path.c_str(), false); + FileSpec profilePath(llvm::StringRef(home_dir_path.c_str()), false); profilePath.AppendPathComponent(".lldbinit"); std::string init_file_path = profilePath.GetPath(); @@ -2146,7 +2152,7 @@ } if (!init_file && !m_skip_lldbinit_files) - init_file.SetFile(init_file_path.c_str(), false); + init_file.SetFile(llvm::StringRef(init_file_path.c_str()), false); } // If the file exists, tell HandleCommand to 'source' it; this will do the @@ -2720,14 +2726,14 @@ if (!result.GetImmediateOutputStream()) { const char *output = result.GetOutputData(); if (output && output[0]) - io_handler.GetOutputStreamFile()->PutCString(output); + io_handler.GetOutputStreamFile()->PutCString(llvm::StringRef(output)); } // Now emit the command error text from the command we just executed if (!result.GetImmediateErrorStream()) { const char *error = result.GetErrorData(); if (error && error[0]) - io_handler.GetErrorStreamFile()->PutCString(error); + io_handler.GetErrorStreamFile()->PutCString(llvm::StringRef(error)); } } @@ -2932,7 +2938,8 @@ ExtractCommand(scratch_command, next_word, suffix, quote_char); if (cmd_obj == nullptr) { std::string full_name; - bool is_alias = GetAliasFullName(next_word.c_str(), full_name); + bool is_alias = + GetAliasFullName(llvm::StringRef(next_word.c_str()), full_name); cmd_obj = GetCommandObject(next_word, &matches); bool is_real_command = (is_alias == false) || @@ -2940,8 +2947,8 @@ if (!is_real_command) { matches.Clear(); std::string alias_result; - cmd_obj = BuildAliasResult(full_name.c_str(), scratch_command, - alias_result, result); + cmd_obj = BuildAliasResult(llvm::StringRef(full_name.c_str()), + scratch_command, alias_result, result); revised_command_line.Printf("%s", alias_result.c_str()); if (cmd_obj) { wants_raw_input = cmd_obj->WantsRawCommandString(); Index: lldb/source/Interpreter/CommandObject.cpp =================================================================== --- lldb/source/Interpreter/CommandObject.cpp +++ lldb/source/Interpreter/CommandObject.cpp @@ -985,7 +985,7 @@ bool CommandObjectParsed::Execute(const char *args_string, CommandReturnObject &result) { bool handled = false; - Args cmd_args(args_string); + Args cmd_args((llvm::StringRef(args_string))); if (HasOverrideCallback()) { Args full_args(GetCommandName()); full_args.AppendArguments(cmd_args); @@ -997,7 +997,8 @@ if (!entry.Value.ref.empty() && entry.Value.ref.front() == '`') { cmd_args.ReplaceArgumentAtIndex( entry.Index, - m_interpreter.ProcessEmbeddedScriptCommands(entry.Value.c_str())); + llvm::StringRef(m_interpreter.ProcessEmbeddedScriptCommands( + entry.Value.c_str()))); } } Index: lldb/source/Interpreter/CommandObjectRegexCommand.cpp =================================================================== --- lldb/source/Interpreter/CommandObjectRegexCommand.cpp +++ lldb/source/Interpreter/CommandObjectRegexCommand.cpp @@ -42,7 +42,7 @@ for (pos = m_entries.begin(); pos != end; ++pos) { RegularExpression::Match regex_match(m_max_matches); - if (pos->regex.Execute(command, ®ex_match)) { + if (pos->regex.Execute(llvm::StringRef(command), ®ex_match)) { std::string new_command(pos->command); std::string match_str; char percent_var[8]; Index: lldb/source/Interpreter/CommandReturnObject.cpp =================================================================== --- lldb/source/Interpreter/CommandReturnObject.cpp +++ lldb/source/Interpreter/CommandReturnObject.cpp @@ -101,7 +101,7 @@ void CommandReturnObject::AppendRawWarning(const char *in_string) { if (in_string && in_string[0]) - GetErrorStream().PutCString(in_string); + GetErrorStream().PutCString(llvm::StringRef(in_string)); } void CommandReturnObject::AppendError(const char *in_string) { @@ -130,7 +130,7 @@ void CommandReturnObject::AppendRawError(const char *in_string) { if (in_string && in_string[0]) - GetErrorStream().PutCString(in_string); + GetErrorStream().PutCString(llvm::StringRef(in_string)); } void CommandReturnObject::SetStatus(ReturnStatus status) { m_status = status; } Index: lldb/source/Interpreter/OptionValueArch.cpp =================================================================== --- lldb/source/Interpreter/OptionValueArch.cpp +++ lldb/source/Interpreter/OptionValueArch.cpp @@ -33,7 +33,7 @@ if (m_current_value.IsValid()) { const char *arch_name = m_current_value.GetArchitectureName(); if (arch_name) - strm.PutCString(arch_name); + strm.PutCString(llvm::StringRef(arch_name)); } } } Index: lldb/source/Interpreter/OptionValueArray.cpp =================================================================== --- lldb/source/Interpreter/OptionValueArray.cpp +++ lldb/source/Interpreter/OptionValueArray.cpp @@ -72,7 +72,7 @@ Error OptionValueArray::SetValueFromString(llvm::StringRef value, VarSetOperationType op) { - Args args(value.str().c_str()); + Args args(llvm::StringRef(value.str().c_str())); Error error = SetArgs(args, op); if (error.Success()) NotifyValueChanged(); Index: lldb/source/Interpreter/OptionValueBoolean.cpp =================================================================== --- lldb/source/Interpreter/OptionValueBoolean.cpp +++ lldb/source/Interpreter/OptionValueBoolean.cpp @@ -31,7 +31,7 @@ if (dump_mask & eDumpOptionValue) { if (dump_mask & eDumpOptionType) strm.PutCString(" = "); - strm.PutCString(m_current_value ? "true" : "false"); + strm.PutCString(llvm::StringRef(m_current_value ? "true" : "false")); } } Index: lldb/source/Interpreter/OptionValueDictionary.cpp =================================================================== --- lldb/source/Interpreter/OptionValueDictionary.cpp +++ lldb/source/Interpreter/OptionValueDictionary.cpp @@ -198,7 +198,7 @@ Error OptionValueDictionary::SetValueFromString(llvm::StringRef value, VarSetOperationType op) { - Args args(value.str().c_str()); + Args args(llvm::StringRef(value.str().c_str())); Error error = SetArgs(args, op); if (error.Success()) NotifyValueChanged(); Index: lldb/source/Interpreter/OptionValueEnumeration.cpp =================================================================== --- lldb/source/Interpreter/OptionValueEnumeration.cpp +++ lldb/source/Interpreter/OptionValueEnumeration.cpp @@ -120,7 +120,7 @@ if (s && s[0]) { for (size_t i = 0; i < num_enumerators; ++i) { llvm::StringRef name = m_enumerations.GetCStringAtIndex(i); - if (name.startswith(s)) + if (name.startswith(llvm::StringRef(s))) matches.AppendString(name); } } else { Index: lldb/source/Interpreter/OptionValueFileSpec.cpp =================================================================== --- lldb/source/Interpreter/OptionValueFileSpec.cpp +++ lldb/source/Interpreter/OptionValueFileSpec.cpp @@ -80,7 +80,7 @@ // or whitespace. value = value.trim("\"' \t"); m_value_was_set = true; - m_current_value.SetFile(value.str().c_str(), m_resolve); + m_current_value.SetFile(llvm::StringRef(value.str().c_str()), m_resolve); m_data_sp.reset(); m_data_mod_time.Clear(); NotifyValueChanged(); Index: lldb/source/Interpreter/OptionValueFileSpecLIst.cpp =================================================================== --- lldb/source/Interpreter/OptionValueFileSpecLIst.cpp +++ lldb/source/Interpreter/OptionValueFileSpecLIst.cpp @@ -41,7 +41,7 @@ Error OptionValueFileSpecList::SetValueFromString(llvm::StringRef value, VarSetOperationType op) { Error error; - Args args(value.str().c_str()); + Args args(llvm::StringRef(value.str().c_str())); const size_t argc = args.GetArgumentCount(); switch (op) { @@ -61,7 +61,7 @@ count); } else { for (size_t i = 1; i < argc; ++i, ++idx) { - FileSpec file(args.GetArgumentAtIndex(i), false); + FileSpec file(llvm::StringRef(args.GetArgumentAtIndex(i)), false); if (idx < count) m_current_value.Replace(idx, file); else @@ -83,7 +83,7 @@ if (argc > 0) { m_value_was_set = true; for (size_t i = 0; i < argc; ++i) { - FileSpec file(args.GetArgumentAtIndex(i), false); + FileSpec file(llvm::StringRef(args.GetArgumentAtIndex(i)), false); m_current_value.Append(file); } NotifyValueChanged(); @@ -107,7 +107,7 @@ if (op == eVarSetOperationInsertAfter) ++idx; for (size_t i = 1; i < argc; ++i, ++idx) { - FileSpec file(args.GetArgumentAtIndex(i), false); + FileSpec file(llvm::StringRef(args.GetArgumentAtIndex(i)), false); m_current_value.Insert(idx, file); } NotifyValueChanged(); Index: lldb/source/Interpreter/OptionValueFormat.cpp =================================================================== --- lldb/source/Interpreter/OptionValueFormat.cpp +++ lldb/source/Interpreter/OptionValueFormat.cpp @@ -27,7 +27,8 @@ if (dump_mask & eDumpOptionValue) { if (dump_mask & eDumpOptionType) strm.PutCString(" = "); - strm.PutCString(FormatManager::GetFormatAsCString(m_current_value)); + strm.PutCString( + llvm::StringRef(FormatManager::GetFormatAsCString(m_current_value))); } } Index: lldb/source/Interpreter/OptionValueLanguage.cpp =================================================================== --- lldb/source/Interpreter/OptionValueLanguage.cpp +++ lldb/source/Interpreter/OptionValueLanguage.cpp @@ -28,7 +28,8 @@ if (dump_mask & eDumpOptionValue) { if (dump_mask & eDumpOptionType) strm.PutCString(" = "); - strm.PutCString(Language::GetNameForLanguageType(m_current_value)); + strm.PutCString( + llvm::StringRef(Language::GetNameForLanguageType(m_current_value))); } } Index: lldb/source/Interpreter/OptionValuePathMappings.cpp =================================================================== --- lldb/source/Interpreter/OptionValuePathMappings.cpp +++ lldb/source/Interpreter/OptionValuePathMappings.cpp @@ -23,7 +23,7 @@ namespace { static bool VerifyPathExists(const char *path) { if (path && path[0]) - return FileSpec(path, false).Exists(); + return FileSpec(llvm::StringRef(path), false).Exists(); else return false; } @@ -43,7 +43,7 @@ Error OptionValuePathMappings::SetValueFromString(llvm::StringRef value, VarSetOperationType op) { Error error; - Args args(value.str().c_str()); + Args args(llvm::StringRef(value.str().c_str())); const size_t argc = args.GetArgumentCount(); switch (op) { Index: lldb/source/Interpreter/OptionValueProperties.cpp =================================================================== --- lldb/source/Interpreter/OptionValueProperties.cpp +++ lldb/source/Interpreter/OptionValueProperties.cpp @@ -591,7 +591,7 @@ if (value_sp) { if (!value_sp->ValueIsTransparent()) { if (dump_mask & eDumpOptionName) - strm.PutCString(property_path); + strm.PutCString(llvm::StringRef(property_path)); if (dump_mask & ~eDumpOptionName) strm.PutChar(' '); } Index: lldb/source/Interpreter/Options.cpp =================================================================== --- lldb/source/Interpreter/Options.cpp +++ lldb/source/Interpreter/Options.cpp @@ -371,7 +371,7 @@ return false; if (header && header[0]) - strm.PutCString(header); + strm.PutCString(llvm::StringRef(header)); if (show_optional && !opt_def.required) strm.PutChar('['); @@ -396,7 +396,7 @@ if (show_optional && !opt_def.required) strm.PutChar(']'); if (footer && footer[0]) - strm.PutCString(footer); + strm.PutCString(llvm::StringRef(footer)); return true; } @@ -853,7 +853,7 @@ cur_arg_pos != -1) { const char *module_name = input.GetArgumentAtIndex(cur_arg_pos); if (module_name) { - FileSpec module_spec(module_name, false); + FileSpec module_spec(llvm::StringRef(module_name), false); lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget(); // Search filters require a target... Index: lldb/source/Interpreter/Property.cpp =================================================================== --- lldb/source/Interpreter/Property.cpp +++ lldb/source/Interpreter/Property.cpp @@ -103,7 +103,8 @@ // be resolved or not const bool resolve = definition.default_uint_value != 0; m_value_sp.reset(new OptionValueFileSpec( - FileSpec(definition.default_cstr_value, resolve), resolve)); + FileSpec(llvm::StringRef(definition.default_cstr_value), resolve), + resolve)); break; } Index: lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.cpp =================================================================== --- lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.cpp +++ lldb/source/Plugins/Disassembler/llvm/DisassemblerLLVMC.cpp @@ -736,7 +736,7 @@ if (op.m_negative) { s.PutCString("-"); } - s.PutCString(llvm::to_string(op.m_immediate).c_str()); + s.PutCString(llvm::StringRef(llvm::to_string(op.m_immediate).c_str())); break; case Operand::Type::Invalid: s.PutCString("Invalid"); @@ -749,7 +749,7 @@ s.PutCString(")"); break; case Operand::Type::Register: - s.PutCString(op.m_register.AsCString()); + s.PutCString(llvm::StringRef(op.m_register.AsCString())); break; case Operand::Type::Sum: s.PutCString("("); @@ -894,14 +894,16 @@ } m_instr_info_ap.reset(curr_target->createMCInstrInfo()); - m_reg_info_ap.reset(curr_target->createMCRegInfo(triple)); + m_reg_info_ap.reset(curr_target->createMCRegInfo(llvm::StringRef(triple))); - m_subtarget_info_ap.reset( - curr_target->createMCSubtargetInfo(triple, cpu, features_str)); + m_subtarget_info_ap.reset(curr_target->createMCSubtargetInfo( + llvm::StringRef(triple), llvm::StringRef(cpu), + llvm::StringRef(features_str))); std::unique_ptr reg_info( - curr_target->createMCRegInfo(triple)); - m_asm_info_ap.reset(curr_target->createMCAsmInfo(*reg_info, triple)); + curr_target->createMCRegInfo(llvm::StringRef(triple))); + m_asm_info_ap.reset( + curr_target->createMCAsmInfo(*reg_info, llvm::StringRef(triple))); if (m_instr_info_ap.get() == NULL || m_reg_info_ap.get() == NULL || m_subtarget_info_ap.get() == NULL || m_asm_info_ap.get() == NULL) { @@ -916,15 +918,17 @@ *m_subtarget_info_ap.get(), *m_context_ap.get())); if (m_disasm_ap.get() && m_context_ap.get()) { std::unique_ptr RelInfo( - curr_target->createMCRelocationInfo(triple, *m_context_ap.get())); + curr_target->createMCRelocationInfo(llvm::StringRef(triple), + *m_context_ap.get())); if (!RelInfo) { m_is_valid = false; return; } std::unique_ptr symbolizer_up( - curr_target->createMCSymbolizer( - triple, NULL, DisassemblerLLVMC::SymbolLookupCallback, - (void *)&owner, m_context_ap.get(), std::move(RelInfo))); + curr_target->createMCSymbolizer(llvm::StringRef(triple), NULL, + DisassemblerLLVMC::SymbolLookupCallback, + (void *)&owner, m_context_ap.get(), + std::move(RelInfo))); m_disasm_ap->setSymbolizer(std::move(symbolizer_up)); unsigned asm_printer_variant; Index: lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.cpp =================================================================== --- lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.cpp +++ lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.cpp @@ -608,7 +608,7 @@ return false; FileSpec file_spec; - file_spec.SetFile(m_name.c_str(), false); + file_spec.SetFile(llvm::StringRef(m_name.c_str()), false); ModuleSP memory_module_sp = process->ReadModuleFromMemory(file_spec, m_load_address); @@ -764,7 +764,7 @@ PlatformDarwinKernel::GetPluginNameStatic()); if (platform_name == g_platform_name) { ModuleSpec kext_bundle_module_spec(module_spec); - FileSpec kext_filespec(m_name.c_str(), false); + FileSpec kext_filespec(llvm::StringRef(m_name.c_str()), false); kext_bundle_module_spec.GetFileSpec() = kext_filespec; platform_sp->GetSharedModule( kext_bundle_module_spec, process, m_module_sp, Index: lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp =================================================================== --- lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp +++ lldb/source/Plugins/DynamicLoader/Hexagon-DYLD/DynamicLoaderHexagonDYLD.cpp @@ -369,7 +369,7 @@ E = m_rendezvous.loaded_end(); for (I = m_rendezvous.loaded_begin(); I != E; ++I) { - FileSpec file(I->path.c_str(), true); + FileSpec file(llvm::StringRef(I->path.c_str()), true); ModuleSP module_sp = LoadModuleAtAddress(file, I->link_addr, I->base_addr, true); if (module_sp.get()) { @@ -393,7 +393,7 @@ E = m_rendezvous.unloaded_end(); for (I = m_rendezvous.unloaded_begin(); I != E; ++I) { - FileSpec file(I->path.c_str(), true); + FileSpec file(llvm::StringRef(I->path.c_str()), true); ModuleSpec module_spec(file); ModuleSP module_sp = loaded_modules.FindFirstModule(module_spec); @@ -487,7 +487,7 @@ for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) { const char *module_path = I->path.c_str(); - FileSpec file(module_path, false); + FileSpec file(llvm::StringRef(module_path), false); ModuleSP module_sp = LoadModuleAtAddress(file, I->link_addr, I->base_addr, true); if (module_sp.get()) { Index: lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp =================================================================== --- lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp +++ lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp @@ -377,7 +377,10 @@ image_infos[i].mod_date = image->GetValueForKey("mod_date")->GetAsInteger()->GetValue(); image_infos[i].file_spec.SetFile( - image->GetValueForKey("pathname")->GetAsString()->GetValue().c_str(), + llvm::StringRef(image->GetValueForKey("pathname") + ->GetAsString() + ->GetValue() + .c_str()), false); StructuredData::Dictionary *mh = Index: lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp =================================================================== --- lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp +++ lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.cpp @@ -907,7 +907,7 @@ const lldb::offset_t name_offset = load_cmd_offset + data.GetU32(&offset); const char *path = data.PeekCStr(name_offset); - lc_id_dylinker->SetFile(path, true); + lc_id_dylinker->SetFile(llvm::StringRef(path), true); } break; Index: lldb/source/Plugins/ExpressionParser/Clang/ASTDumper.cpp =================================================================== --- lldb/source/Plugins/ExpressionParser/Clang/ASTDumper.cpp +++ lldb/source/Plugins/ExpressionParser/Clang/ASTDumper.cpp @@ -107,5 +107,5 @@ } void ASTDumper::ToStream(lldb::StreamSP &stream) { - stream->PutCString(m_dump.c_str()); + stream->PutCString(llvm::StringRef(m_dump.c_str())); } Index: lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.cpp =================================================================== --- lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.cpp +++ lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.cpp @@ -921,8 +921,8 @@ const std::string &decl_name_string = decl_name.getAsString(); std::string decl_name_string_without_colon(decl_name_string.c_str(), decl_name_string.length() - 1); - IdentifierInfo *ident = - &original_ctx->Idents.get(decl_name_string_without_colon.c_str()); + IdentifierInfo *ident = &original_ctx->Idents.get( + llvm::StringRef(decl_name_string_without_colon.c_str())); original_selector = original_ctx->Selectors.getSelector(1, &ident); } else { SmallVector idents; Index: lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp =================================================================== --- lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp +++ lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp @@ -592,7 +592,8 @@ if (!created_main_file) { std::unique_ptr memory_buffer = - MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__); + MemoryBuffer::getMemBufferCopy(llvm::StringRef(expr_text), + __FUNCTION__); source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer))); } @@ -748,7 +749,7 @@ llvm::Module *module, const char *orig_name) { for (const auto &func : module->getFunctionList()) { const StringRef &name = func.getName(); - if (name.find(orig_name) != StringRef::npos) { + if (name.find(llvm::StringRef(orig_name)) != StringRef::npos) { mangled_name.SetString(name); return true; } Index: lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp =================================================================== --- lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp +++ lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp @@ -131,7 +131,7 @@ for (IDAndDiagnostic &diag : m_diagnostics) { switch (diag.first) { default: - error_stream.PutCString(diag.second.c_str()); + error_stream.PutCString(llvm::StringRef(diag.second.c_str())); error_stream.PutChar('\n'); break; case clang::DiagnosticsEngine::Level::Ignored: @@ -631,10 +631,10 @@ std::unique_ptr source_buffer = llvm::MemoryBuffer::getMemBuffer( "extern int __lldb __attribute__((unavailable));", - ModuleImportBufferName); + llvm::StringRef(ModuleImportBufferName)); - invocation->getPreprocessorOpts().addRemappedFile(ModuleImportBufferName, - source_buffer.release()); + invocation->getPreprocessorOpts().addRemappedFile( + llvm::StringRef(ModuleImportBufferName), source_buffer.release()); std::unique_ptr instance( new clang::CompilerInstance); Index: lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.cpp =================================================================== --- lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.cpp +++ lldb/source/Plugins/ExpressionParser/Clang/IRForTarget.cpp @@ -198,7 +198,7 @@ if (log) log->Printf("Result name: \"%s\"", result_name); - Value *result_value = m_module->getNamedValue(result_name); + Value *result_value = m_module->getNamedValue(llvm::StringRef(result_name)); if (!result_value) { if (log) Index: lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp =================================================================== --- lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp +++ lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp @@ -507,7 +507,8 @@ const bool is_synthesized = false; clang::ObjCIvarDecl *ivar_decl = clang::ObjCIvarDecl::Create( *m_ast_ctx.getASTContext(), interface_decl, clang::SourceLocation(), - clang::SourceLocation(), &m_ast_ctx.getASTContext()->Idents.get(name), + clang::SourceLocation(), + &m_ast_ctx.getASTContext()->Idents.get(llvm::StringRef(name)), ClangUtil::GetQualType(ivar_type), type_source_info, // TypeSourceInfo * clang::ObjCIvarDecl::Public, 0, is_synthesized); Index: lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp =================================================================== --- lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp +++ lldb/source/Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.cpp @@ -2246,7 +2246,7 @@ "Allocation information not available"); // Check we can read from file - FileSpec file(path, true); + FileSpec file(llvm::StringRef(path), true); if (!file.Exists()) { strm.Printf("Error: File %s does not exist", path); strm.EOL(); @@ -2470,7 +2470,7 @@ "Allocation information not available"); // Check we can create writable file - FileSpec file_spec(path, true); + FileSpec file_spec(llvm::StringRef(path), true); File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate); if (!file) { @@ -3826,7 +3826,7 @@ break; case 'c': { auto coord = RSCoordinate{}; - if (!ParseCoordinate(option_val, coord)) + if (!ParseCoordinate(llvm::StringRef(option_val), coord)) err.SetErrorStringWithFormat("unable to parse coordinate for %s", option_val); else { @@ -3975,7 +3975,7 @@ switch (short_option) { case 'c': { auto coord = RSCoordinate{}; - if (!ParseCoordinate(option_arg, coord)) + if (!ParseCoordinate(llvm::StringRef(option_arg), coord)) err.SetErrorStringWithFormat( "Couldn't parse coordinate '%s', should be in format 'x,y,z'.", option_arg); @@ -4255,7 +4255,7 @@ switch (short_option) { case 'f': - m_outfile.SetFile(option_arg, true); + m_outfile.SetFile(llvm::StringRef(option_arg), true); if (m_outfile.Exists()) { m_outfile.Clear(); err.SetErrorStringWithFormat("file already exists: '%s'", option_arg); Index: lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp =================================================================== --- lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp +++ lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp @@ -972,7 +972,7 @@ FileSpecList file_spec_list; if (!m_gnu_debuglink_file.empty()) { - FileSpec file_spec(m_gnu_debuglink_file.c_str(), false); + FileSpec file_spec(llvm::StringRef(m_gnu_debuglink_file.c_str()), false); file_spec_list.Append(file_spec); } return file_spec_list; @@ -1126,7 +1126,7 @@ uint32_t str_index = static_cast(symbol.d_val); const char *lib_name = dynstr_data.PeekCStr(str_index); - m_filespec_ap->Append(FileSpec(lib_name, true)); + m_filespec_ap->Append(FileSpec(llvm::StringRef(lib_name), true)); } } @@ -1430,7 +1430,7 @@ return; Offset = Offset + sizeof(uint32_t); // Section Length - llvm::StringRef VendorName = data.GetCStr(&Offset); + llvm::StringRef VendorName = llvm::StringRef(data.GetCStr(&Offset)); if (VendorName != "aeabi") return; Index: lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp =================================================================== --- lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp +++ lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp @@ -2180,7 +2180,7 @@ uint32_t name_offset = cmd_offset + m_data.GetU32(&offset); const char *path = m_data.PeekCStr(name_offset); if (path) { - FileSpec file_spec(path, false); + FileSpec file_spec(llvm::StringRef(path), false); // Strip the path if there is @rpath, @executable, etc so we just use // the basename if (path[0] == '@') @@ -3936,8 +3936,8 @@ symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value); if (symbol_name && symbol_name[0]) { - type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1, - eSymbolTypeData); + type = ObjectFile::GetSymbolTypeFromName( + llvm::StringRef(symbol_name + 1), eSymbolTypeData); } break; @@ -4051,10 +4051,11 @@ // and the second is the directory for the source file so // you end up with // a path that looks like "/tmp/src//tmp/src/" - FileSpec so_dir(so_path, false); + FileSpec so_dir(llvm::StringRef(so_path), false); if (!so_dir.Exists()) { - so_dir.SetFile(&full_so_path[double_slash_pos + 1], - false); + so_dir.SetFile( + llvm::StringRef(&full_so_path[double_slash_pos + 1]), + false); if (so_dir.Exists()) { // Trim off the incorrect path full_so_path.erase(0, double_slash_pos + 1); @@ -5056,7 +5057,7 @@ if (strncmp(path, "@rpath", strlen("@rpath")) == 0) rpath_relative_paths.push_back(path + strlen("@rpath")); } else { - FileSpec file_spec(path, resolve_path); + FileSpec file_spec(llvm::StringRef(path), resolve_path); if (files.AppendIfUnique(file_spec)) count++; } Index: lldb/source/Plugins/Platform/Android/PlatformAndroid.cpp =================================================================== --- lldb/source/Plugins/Platform/Android/PlatformAndroid.cpp +++ lldb/source/Plugins/Platform/Android/PlatformAndroid.cpp @@ -198,7 +198,7 @@ FileSpec::ePathSyntaxPosix); if (source_spec.IsRelative()) source_spec = GetRemoteWorkingDirectory().CopyByAppendingPathComponent( - source_spec.GetCString(false)); + llvm::StringRef(source_spec.GetCString(false))); Error error; auto sync_service = GetSyncService(error); @@ -243,7 +243,7 @@ FileSpec::ePathSyntaxPosix); if (destination_spec.IsRelative()) destination_spec = GetRemoteWorkingDirectory().CopyByAppendingPathComponent( - destination_spec.GetCString(false)); + llvm::StringRef(destination_spec.GetCString(false))); // TODO: Set correct uid and gid on remote file. Error error; @@ -345,7 +345,7 @@ log->Printf("Failed to remove temp directory: %s", error.AsCString()); }); - FileSpec symfile_platform_filespec(tmpdir.c_str(), false); + FileSpec symfile_platform_filespec(llvm::StringRef(tmpdir.c_str()), false); symfile_platform_filespec.AppendPathComponent("symbolized.oat"); // Execute oatdump on the remote device to generate a file with symtab Index: lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp =================================================================== --- lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp +++ lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp @@ -218,8 +218,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString( - resolved_module_spec.GetArchitecture().GetArchitectureName()); + arch_names.PutCString(llvm::StringRef( + resolved_module_spec.GetArchitecture().GetArchitectureName())); } if (error.Fail() || !exe_module_sp) { Index: lldb/source/Plugins/Platform/Kalimba/PlatformKalimba.cpp =================================================================== --- lldb/source/Plugins/Platform/Kalimba/PlatformKalimba.cpp +++ lldb/source/Plugins/Platform/Kalimba/PlatformKalimba.cpp @@ -154,8 +154,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString( - resolved_module_spec.GetArchitecture().GetArchitectureName()); + arch_names.PutCString(llvm::StringRef( + resolved_module_spec.GetArchitecture().GetArchitectureName())); } if (error.Fail() || !exe_module_sp) { Index: lldb/source/Plugins/Platform/Linux/PlatformLinux.cpp =================================================================== --- lldb/source/Plugins/Platform/Linux/PlatformLinux.cpp +++ lldb/source/Plugins/Platform/Linux/PlatformLinux.cpp @@ -308,8 +308,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString( - resolved_module_spec.GetArchitecture().GetArchitectureName()); + arch_names.PutCString(llvm::StringRef( + resolved_module_spec.GetArchitecture().GetArchitectureName())); } if (error.Fail() || !exe_module_sp) { Index: lldb/source/Plugins/Platform/MacOSX/PlatformAppleSimulator.cpp =================================================================== --- lldb/source/Plugins/Platform/MacOSX/PlatformAppleSimulator.cpp +++ lldb/source/Plugins/Platform/MacOSX/PlatformAppleSimulator.cpp @@ -230,7 +230,7 @@ developer_dir); const bool resolve_path = true; m_core_simulator_framework_path = - FileSpec(cs_path.GetData(), resolve_path); + FileSpec(llvm::StringRef(cs_path.GetData()), resolve_path); } } Index: lldb/source/Plugins/Platform/MacOSX/PlatformAppleTVSimulator.cpp =================================================================== --- lldb/source/Plugins/Platform/MacOSX/PlatformAppleTVSimulator.cpp +++ lldb/source/Plugins/Platform/MacOSX/PlatformAppleTVSimulator.cpp @@ -221,7 +221,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString(platform_arch.GetArchitectureName()); + arch_names.PutCString( + llvm::StringRef(platform_arch.GetArchitectureName())); } } Index: lldb/source/Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.cpp =================================================================== --- lldb/source/Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.cpp +++ lldb/source/Plugins/Platform/MacOSX/PlatformAppleWatchSimulator.cpp @@ -223,7 +223,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString(platform_arch.GetArchitectureName()); + arch_names.PutCString( + llvm::StringRef(platform_arch.GetArchitectureName())); } } Index: lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp =================================================================== --- lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp +++ lldb/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp @@ -133,9 +133,10 @@ "%s/../Python/%s.py", symfile_spec.GetDirectory().GetCString(), original_module_basename.c_str()); - FileSpec script_fspec(path_string.GetData(), true); - FileSpec orig_script_fspec(original_path_string.GetData(), - true); + FileSpec script_fspec(llvm::StringRef(path_string.GetData()), + true); + FileSpec orig_script_fspec( + llvm::StringRef(original_path_string.GetData()), true); // if we did some replacements of reserved characters, and a // file with the untampered name @@ -286,8 +287,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString( - resolved_module_spec.GetArchitecture().GetArchitectureName()); + arch_names.PutCString(llvm::StringRef( + resolved_module_spec.GetArchitecture().GetArchitectureName())); } if (error.Fail() || !exe_module_sp) { @@ -373,7 +374,7 @@ if (!cache_path.empty()) { std::string module_path(module_spec.GetFileSpec().GetPath()); cache_path.append(module_path); - FileSpec module_cache_spec(cache_path.c_str(), false); + FileSpec module_cache_spec(llvm::StringRef(cache_path.c_str()), false); // if rsync is supported, always bring in the file - rsync will be very // efficient @@ -1294,7 +1295,7 @@ if (xcode_select_prefix_dir) xcode_dir_path.append(xcode_select_prefix_dir); xcode_dir_path.append("/usr/share/xcode-select/xcode_dir_path"); - temp_file_spec.SetFile(xcode_dir_path.c_str(), false); + temp_file_spec.SetFile(llvm::StringRef(xcode_dir_path.c_str()), false); size_t bytes_read = temp_file_spec.ReadFileContents( 0, developer_dir_path, sizeof(developer_dir_path), NULL); if (bytes_read > 0) { @@ -1370,7 +1371,7 @@ FileSpecList bp_modules; for (size_t i = 0; i < llvm::array_lengthof(g_bp_modules); i++) { const char *bp_module = g_bp_modules[i]; - bp_modules.Append(FileSpec(bp_module, false)); + bp_modules.Append(FileSpec(llvm::StringRef(bp_module), false)); } bool internal = true; @@ -1436,7 +1437,7 @@ size_t pos = path_to_shlib.rfind(substr); if (pos != std::string::npos) { path_to_shlib.erase(pos + strlen(substr)); - FileSpec ret(path_to_shlib.c_str(), false); + FileSpec ret(llvm::StringRef(path_to_shlib.c_str()), false); FileSpec xcode_binary_path = ret; xcode_binary_path.AppendPathComponent("MacOS"); @@ -1478,8 +1479,8 @@ if (!g_xcode_filespec) { const char *developer_dir_env_var = getenv("DEVELOPER_DIR"); if (developer_dir_env_var && developer_dir_env_var[0]) { - g_xcode_filespec = - CheckPathForXcode(FileSpec(developer_dir_env_var, true)); + g_xcode_filespec = CheckPathForXcode( + FileSpec(llvm::StringRef(developer_dir_env_var), true)); } // Fall back to using "xcrun" to find the selected Xcode @@ -1503,7 +1504,8 @@ } output.append("/.."); - g_xcode_filespec = CheckPathForXcode(FileSpec(output.c_str(), false)); + g_xcode_filespec = CheckPathForXcode( + FileSpec(llvm::StringRef(output.c_str()), false)); } } } @@ -1538,7 +1540,7 @@ llvm::StringRef version_part; - if (sdk_name.startswith(sdk_strings[(int)desired_type])) { + if (sdk_name.startswith(llvm::StringRef(sdk_strings[(int)desired_type]))) { version_part = sdk_name.drop_front(strlen(sdk_strings[(int)desired_type])); } else { @@ -1604,9 +1606,9 @@ enumerator_info.sdk_type = sdk_type; - FileSpec::EnumerateDirectory(sdks_spec.GetPath().c_str(), find_directories, - find_files, find_other, DirectoryEnumerator, - &enumerator_info); + FileSpec::EnumerateDirectory(llvm::StringRef(sdks_spec.GetPath().c_str()), + find_directories, find_files, find_other, + DirectoryEnumerator, &enumerator_info); if (enumerator_info.found_path.IsDirectory()) return enumerator_info.found_path; @@ -1655,7 +1657,7 @@ StreamString native_sdk_name; native_sdk_name.Printf("MacOSX%u.%u.sdk", major, minor); native_sdk_spec.AppendPathComponent( - native_sdk_name.GetString().c_str()); + llvm::StringRef(native_sdk_name.GetString().c_str())); if (native_sdk_spec.Exists()) { return native_sdk_spec; @@ -1742,24 +1744,24 @@ switch (sdk_type) { case SDKType::iPhoneOS: minimum_version_option.PutCString("-mios-version-min="); - minimum_version_option.PutCString( + minimum_version_option.PutCString(llvm::StringRef( clang::VersionTuple(versions[0], versions[1], versions[2]) .getAsString() - .c_str()); + .c_str())); break; case SDKType::iPhoneSimulator: minimum_version_option.PutCString("-mios-simulator-version-min="); - minimum_version_option.PutCString( + minimum_version_option.PutCString(llvm::StringRef( clang::VersionTuple(versions[0], versions[1], versions[2]) .getAsString() - .c_str()); + .c_str())); break; case SDKType::MacOSX: minimum_version_option.PutCString("-mmacosx-version-min="); - minimum_version_option.PutCString( + minimum_version_option.PutCString(llvm::StringRef( clang::VersionTuple(versions[0], versions[1], versions[2]) .getAsString() - .c_str()); + .c_str())); } options.push_back(minimum_version_option.GetString()); } Index: lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.cpp =================================================================== --- lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.cpp +++ lldb/source/Plugins/Platform/MacOSX/PlatformDarwinKernel.cpp @@ -427,9 +427,9 @@ const bool find_directories = true; const bool find_files = false; const bool find_other = false; - FileSpec::EnumerateDirectory(dir.c_str(), find_directories, find_files, - find_other, FindKDKandSDKDirectoriesInDirectory, - this); + FileSpec::EnumerateDirectory(llvm::StringRef(dir.c_str()), find_directories, + find_files, find_other, + FindKDKandSDKDirectoriesInDirectory, this); } // Helper function to find *.sdk and *.kdk directories in a given directory. @@ -459,8 +459,8 @@ const bool find_files = true; const bool find_other = true; // I think eFileTypeSymbolicLink are "other"s. FileSpec::EnumerateDirectory( - dir.GetPath().c_str(), find_directories, find_files, find_other, - GetKernelsAndKextsInDirectoryWithRecursion, this); + llvm::StringRef(dir.GetPath().c_str()), find_directories, find_files, + find_other, GetKernelsAndKextsInDirectoryWithRecursion, this); } const uint32_t num_dirs_no_recurse = m_search_directories_no_recursing.size(); for (uint32_t i = 0; i < num_dirs_no_recurse; i++) { @@ -469,8 +469,8 @@ const bool find_files = true; const bool find_other = true; // I think eFileTypeSymbolicLink are "other"s. FileSpec::EnumerateDirectory( - dir.GetPath().c_str(), find_directories, find_files, find_other, - GetKernelsAndKextsInDirectoryNoRecursion, this); + llvm::StringRef(dir.GetPath().c_str()), find_directories, find_files, + find_other, GetKernelsAndKextsInDirectoryNoRecursion, this); } } @@ -544,7 +544,8 @@ const bool find_files = false; const bool find_other = false; FileSpec::EnumerateDirectory( - search_here_too.c_str(), find_directories, find_files, find_other, + llvm::StringRef(search_here_too.c_str()), find_directories, + find_files, find_other, recurse ? GetKernelsAndKextsInDirectoryWithRecursion : GetKernelsAndKextsInDirectoryNoRecursion, baton); Index: lldb/source/Plugins/Platform/MacOSX/PlatformMacOSX.cpp =================================================================== --- lldb/source/Plugins/Platform/MacOSX/PlatformMacOSX.cpp +++ lldb/source/Plugins/Platform/MacOSX/PlatformMacOSX.cpp @@ -220,13 +220,13 @@ "SDKs/MacOSX%u.%u.sdk", xcode_contents_path.c_str(), versions[0], versions[1]); - fspec.SetFile(sdk_path.GetString().c_str(), false); + fspec.SetFile(llvm::StringRef(sdk_path.GetString().c_str()), false); if (fspec.Exists()) return ConstString(sdk_path.GetString().c_str()); } if (!default_xcode_sdk.empty()) { - fspec.SetFile(default_xcode_sdk.c_str(), false); + fspec.SetFile(llvm::StringRef(default_xcode_sdk.c_str()), false); if (fspec.Exists()) return ConstString(default_xcode_sdk.c_str()); } @@ -270,7 +270,7 @@ std::string cache_path(GetLocalCacheDirectory()); std::string module_path(platform_file.GetPath()); cache_path.append(module_path); - FileSpec module_cache_spec(cache_path.c_str(), false); + FileSpec module_cache_spec(llvm::StringRef(cache_path.c_str()), false); if (module_cache_spec.Exists()) { local_file = module_cache_spec; return Error(); Index: lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleTV.cpp =================================================================== --- lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleTV.cpp +++ lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleTV.cpp @@ -223,8 +223,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString( - resolved_module_spec.GetArchitecture().GetArchitectureName()); + arch_names.PutCString(llvm::StringRef( + resolved_module_spec.GetArchitecture().GetArchitectureName())); } if (error.Fail() || !exe_module_sp) { @@ -271,10 +271,10 @@ const bool find_other = false; SDKDirectoryInfoCollection builtin_sdk_directory_infos; - FileSpec::EnumerateDirectory(m_device_support_directory.c_str(), - find_directories, find_files, find_other, - GetContainedFilesIntoVectorOfStringsCallback, - &builtin_sdk_directory_infos); + FileSpec::EnumerateDirectory( + llvm::StringRef(m_device_support_directory.c_str()), find_directories, + find_files, find_other, GetContainedFilesIntoVectorOfStringsCallback, + &builtin_sdk_directory_infos); // Only add SDK directories that have symbols in them, some SDKs only // contain @@ -530,10 +530,10 @@ const char *paths_to_try[] = {"Symbols", "", "Symbols.Internal", nullptr}; for (size_t i = 0; paths_to_try[i] != nullptr; i++) { - local_file.SetFile(sdkroot_path.c_str(), false); + local_file.SetFile(llvm::StringRef(sdkroot_path.c_str()), false); if (paths_to_try[i][0] != '\0') - local_file.AppendPathComponent(paths_to_try[i]); - local_file.AppendPathComponent(platform_file_path); + local_file.AppendPathComponent(llvm::StringRef(paths_to_try[i])); + local_file.AppendPathComponent(llvm::StringRef(platform_file_path)); local_file.ResolvePath(); if (local_file.Exists()) { if (log) Index: lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.cpp =================================================================== --- lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.cpp +++ lldb/source/Plugins/Platform/MacOSX/PlatformRemoteAppleWatch.cpp @@ -233,8 +233,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString( - resolved_module_spec.GetArchitecture().GetArchitectureName()); + arch_names.PutCString(llvm::StringRef( + resolved_module_spec.GetArchitecture().GetArchitectureName())); } if (error.Fail() || !exe_module_sp) { @@ -281,10 +281,10 @@ const bool find_other = false; SDKDirectoryInfoCollection builtin_sdk_directory_infos; - FileSpec::EnumerateDirectory(m_device_support_directory.c_str(), - find_directories, find_files, find_other, - GetContainedFilesIntoVectorOfStringsCallback, - &builtin_sdk_directory_infos); + FileSpec::EnumerateDirectory( + llvm::StringRef(m_device_support_directory.c_str()), find_directories, + find_files, find_other, GetContainedFilesIntoVectorOfStringsCallback, + &builtin_sdk_directory_infos); // Only add SDK directories that have symbols in them, some SDKs only // contain @@ -452,14 +452,14 @@ m_device_support_directory.assign(device_support_dir); m_device_support_directory.append( "/Platforms/watchOS.platform/DeviceSupport"); - FileSpec platform_device_support_dir(m_device_support_directory.c_str(), - true); + FileSpec platform_device_support_dir( + llvm::StringRef(m_device_support_directory.c_str()), true); if (!platform_device_support_dir.Exists()) { std::string alt_platform_dirname = device_support_dir; alt_platform_dirname.append( "/Platforms/WatchOS.platform/DeviceSupport"); FileSpec alt_platform_device_support_dir( - m_device_support_directory.c_str(), true); + llvm::StringRef(m_device_support_directory.c_str()), true); if (alt_platform_device_support_dir.Exists()) { m_device_support_directory = alt_platform_dirname; } @@ -545,10 +545,10 @@ const char *paths_to_try[] = {"Symbols", "", "Symbols.Internal", nullptr}; for (size_t i = 0; paths_to_try[i] != nullptr; i++) { - local_file.SetFile(sdkroot_path.c_str(), false); + local_file.SetFile(llvm::StringRef(sdkroot_path.c_str()), false); if (paths_to_try[i][0] != '\0') - local_file.AppendPathComponent(paths_to_try[i]); - local_file.AppendPathComponent(platform_file_path); + local_file.AppendPathComponent(llvm::StringRef(paths_to_try[i])); + local_file.AppendPathComponent(llvm::StringRef(platform_file_path)); local_file.ResolvePath(); if (local_file.Exists()) { if (log) Index: lldb/source/Plugins/Platform/MacOSX/PlatformRemoteiOS.cpp =================================================================== --- lldb/source/Plugins/Platform/MacOSX/PlatformRemoteiOS.cpp +++ lldb/source/Plugins/Platform/MacOSX/PlatformRemoteiOS.cpp @@ -228,8 +228,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString( - resolved_module_spec.GetArchitecture().GetArchitectureName()); + arch_names.PutCString(llvm::StringRef( + resolved_module_spec.GetArchitecture().GetArchitectureName())); } if (error.Fail() || !exe_module_sp) { @@ -266,7 +266,8 @@ if (m_sdk_directory_infos.empty()) { // A --sysroot option was supplied - add it to our list of SDKs to check if (m_sdk_sysroot) { - FileSpec sdk_sysroot_fspec(m_sdk_sysroot.GetCString(), true); + FileSpec sdk_sysroot_fspec(llvm::StringRef(m_sdk_sysroot.GetCString()), + true); const SDKDirectoryInfo sdk_sysroot_directory_info(sdk_sysroot_fspec); m_sdk_directory_infos.push_back(sdk_sysroot_directory_info); if (log) { @@ -288,10 +289,10 @@ const bool find_other = false; SDKDirectoryInfoCollection builtin_sdk_directory_infos; - FileSpec::EnumerateDirectory(m_device_support_directory.c_str(), - find_directories, find_files, find_other, - GetContainedFilesIntoVectorOfStringsCallback, - &builtin_sdk_directory_infos); + FileSpec::EnumerateDirectory( + llvm::StringRef(m_device_support_directory.c_str()), find_directories, + find_files, find_other, GetContainedFilesIntoVectorOfStringsCallback, + &builtin_sdk_directory_infos); // Only add SDK directories that have symbols in them, some SDKs only // contain @@ -516,10 +517,10 @@ const char *paths_to_try[] = {"Symbols", "", "Symbols.Internal", nullptr}; for (size_t i = 0; paths_to_try[i] != nullptr; i++) { - local_file.SetFile(sdkroot_path.c_str(), false); + local_file.SetFile(llvm::StringRef(sdkroot_path.c_str()), false); if (paths_to_try[i][0] != '\0') - local_file.AppendPathComponent(paths_to_try[i]); - local_file.AppendPathComponent(platform_file_path); + local_file.AppendPathComponent(llvm::StringRef(paths_to_try[i])); + local_file.AppendPathComponent(llvm::StringRef(platform_file_path)); local_file.ResolvePath(); if (local_file.Exists()) { if (log) Index: lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulator.cpp =================================================================== --- lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulator.cpp +++ lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulator.cpp @@ -227,7 +227,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString(platform_arch.GetArchitectureName()); + arch_names.PutCString( + llvm::StringRef(platform_arch.GetArchitectureName())); } } Index: lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulatorCoreSimulatorSupport.mm =================================================================== --- lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulatorCoreSimulatorSupport.mm +++ lldb/source/Plugins/Platform/MacOSX/PlatformiOSSimulatorCoreSimulatorSupport.mm @@ -410,7 +410,7 @@ // Check in case our file action open wants to open the slave const char *slave_path = launch_info.GetPTY().GetSlaveName(NULL, 0); if (slave_path) { - FileSpec slave_spec(slave_path, false); + FileSpec slave_spec(llvm::StringRef(slave_path), false); if (file_spec == slave_spec) { int slave_fd = launch_info.GetPTY().GetSlaveFileDescriptor(); if (slave_fd == PseudoTerminal::invalid_fd) Index: lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp =================================================================== --- lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp +++ lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp @@ -210,8 +210,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString( - resolved_module_spec.GetArchitecture().GetArchitectureName()); + arch_names.PutCString(llvm::StringRef( + resolved_module_spec.GetArchitecture().GetArchitectureName())); } if (error.Fail() || !exe_module_sp) { Index: lldb/source/Plugins/Platform/Windows/PlatformWindows.cpp =================================================================== --- lldb/source/Plugins/Platform/Windows/PlatformWindows.cpp +++ lldb/source/Plugins/Platform/Windows/PlatformWindows.cpp @@ -256,8 +256,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString( - resolved_module_spec.GetArchitecture().GetArchitectureName()); + arch_names.PutCString(llvm::StringRef( + resolved_module_spec.GetArchitecture().GetArchitectureName())); } if (error.Fail() || !exe_module_sp) { Index: lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp =================================================================== --- lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp +++ lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp @@ -138,8 +138,8 @@ if (idx > 0) arch_names.PutCString(", "); - arch_names.PutCString( - resolved_module_spec.GetArchitecture().GetArchitectureName()); + arch_names.PutCString(llvm::StringRef( + resolved_module_spec.GetArchitecture().GetArchitectureName())); } if (error.Fail() || !exe_module_sp) { Index: lldb/source/Plugins/Process/MacOSX-Kernel/CommunicationKDP.cpp =================================================================== --- lldb/source/Plugins/Process/MacOSX-Kernel/CommunicationKDP.cpp +++ lldb/source/Plugins/Process/MacOSX-Kernel/CommunicationKDP.cpp @@ -370,7 +370,7 @@ request_packet.PutHex16(htons(reply_port)); request_packet.PutHex16(htons(exc_port)); request_packet.SetByteOrder(m_byte_order); - request_packet.PutCString(greeting); + request_packet.PutCString(llvm::StringRef(greeting)); DataExtractor reply_packet; return SendRequestAndGetReply(command, request_packet, reply_packet); } @@ -1190,7 +1190,7 @@ } if (error_desc) { - s.PutCString(error_desc); + s.PutCString(llvm::StringRef(error_desc)); packet.Dump(&s, // Stream to dump to 0, // Offset into "packet" Index: lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp =================================================================== --- lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp +++ lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp @@ -285,7 +285,7 @@ StreamString strm; if (exc_desc) - strm.PutCString(exc_desc); + strm.PutCString(llvm::StringRef(exc_desc)); else strm.Printf("EXC_??? (%" PRIu64 ")", m_value); Index: lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp =================================================================== --- lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp +++ lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp @@ -224,7 +224,7 @@ ModuleSpec exe_module_spec; exe_module_spec.GetArchitecture() = arch; exe_module_spec.GetFileSpec().SetFile( - m_nt_file_entries[0].path.GetCString(), false); + llvm::StringRef(m_nt_file_entries[0].path.GetCString()), false); if (exe_module_spec.GetFileSpec()) { exe_module_sp = GetTarget().GetSharedModule(exe_module_spec); if (exe_module_sp) Index: lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp =================================================================== --- lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp +++ lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp @@ -1015,7 +1015,7 @@ // to the debugserver to use and use it if we do. const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); if (env_debugserver_path) { - debugserver_file_spec.SetFile(env_debugserver_path, false); + debugserver_file_spec.SetFile(llvm::StringRef(env_debugserver_path), false); if (log) log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set " "from environment variable: %s", Index: lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp =================================================================== --- lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp +++ lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp @@ -349,11 +349,11 @@ packet.PutCString("qSupported"); for (uint32_t i = 0; i < features.size(); ++i) { packet.PutCString(i == 0 ? ":" : ";"); - packet.PutCString(features[i].c_str()); + packet.PutCString(llvm::StringRef(features[i].c_str())); } StringExtractorGDBRemote response; - if (SendPacketAndWaitForResponse(packet.GetData(), response, + if (SendPacketAndWaitForResponse(llvm::StringRef(packet.GetData()), response, /*send_async=*/false) == PacketResult::Success) { const char *response_cstr = response.GetStringRef().c_str(); @@ -1074,8 +1074,8 @@ if (avail_type != CompressionType::None) { StringExtractorGDBRemote response; std::string packet = "QEnableCompression:type:" + avail_name + ";"; - if (SendPacketAndWaitForResponse(packet.c_str(), response, false) != - PacketResult::Success) + if (SendPacketAndWaitForResponse(llvm::StringRef(packet.c_str()), response, + false) != PacketResult::Success) return; if (response.IsOKResponse()) { @@ -1773,7 +1773,8 @@ // control the characters in a process name std::string name; extractor.GetHexByteString(name); - process_info.GetExecutableFile().SetFile(name.c_str(), false); + process_info.GetExecutableFile().SetFile(llvm::StringRef(name.c_str()), + false); } else if (name.equals("cputype")) { value.getAsInteger(0, cpu); } else if (name.equals("cpusubtype")) { @@ -2016,7 +2017,7 @@ match_info.GetProcessInfo().GetArchitecture(); const llvm::Triple &triple = match_arch.GetTriple(); packet.PutCString("triple:"); - packet.PutCString(triple.getTriple().c_str()); + packet.PutCString(llvm::StringRef(triple.getTriple().c_str())); packet.PutChar(';'); } } @@ -2699,7 +2700,7 @@ const char *packet = stream.GetData(); StringExtractorGDBRemote response; - if (SendPacketAndWaitForResponse(packet, response, false) != + if (SendPacketAndWaitForResponse(llvm::StringRef(packet), response, false) != PacketResult::Success) return Error("failed to send '%s' packet", packet); @@ -2720,7 +2721,7 @@ const char *packet = stream.GetData(); StringExtractorGDBRemote response; - if (SendPacketAndWaitForResponse(packet, response, false) != + if (SendPacketAndWaitForResponse(llvm::StringRef(packet), response, false) != PacketResult::Success) return Error("failed to send '%s' packet", packet); @@ -3211,7 +3212,8 @@ StringExtractor extractor(value); std::string path; extractor.GetHexByteString(path); - module_spec.GetFileSpec() = FileSpec(path.c_str(), false, arch_spec); + module_spec.GetFileSpec() = + FileSpec(llvm::StringRef(path.c_str()), false, arch_spec); } } @@ -3331,8 +3333,8 @@ << ":read:" << annex.AsCString("") << ":" << std::hex << offset << "," << std::hex << size; - GDBRemoteCommunication::PacketResult res = - SendPacketAndWaitForResponse(packet.str().c_str(), chunk, false); + GDBRemoteCommunication::PacketResult res = SendPacketAndWaitForResponse( + llvm::StringRef(packet.str().c_str()), chunk, false); if (res != GDBRemoteCommunication::PacketResult::Success) { err.SetErrorString("Error sending $qXfer packet"); @@ -3602,7 +3604,7 @@ // data. StreamGDBRemote stream; stream.PutCString("QConfigure"); - stream.PutCString(type_name.AsCString()); + stream.PutCString(llvm::StringRef(type_name.AsCString())); stream.PutChar(':'); if (config_sp) { // Gather the plain-text version of the configuration data. @@ -3619,8 +3621,8 @@ // Send the packet. const bool send_async = false; StringExtractorGDBRemote response; - auto result = SendPacketAndWaitForResponse(stream.GetString().c_str(), - response, send_async); + auto result = SendPacketAndWaitForResponse( + llvm::StringRef(stream.GetString().c_str()), response, send_async); if (result == PacketResult::Success) { // We failed if the config result comes back other than OK. if (strcmp(response.GetStringRef().c_str(), "OK") == 0) { Index: lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp =================================================================== --- lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp +++ lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp @@ -358,8 +358,8 @@ StringExtractor extractor(value); std::string file; extractor.GetHexByteString(file); - match_info.GetProcessInfo().GetExecutableFile().SetFile(file.c_str(), - false); + match_info.GetProcessInfo().GetExecutableFile().SetFile( + llvm::StringRef(file.c_str()), false); } else if (key.equals("name_match")) { NameMatchType name_match = llvm::StringSwitch(value) @@ -645,7 +645,7 @@ packet.GetHexByteString(path); if (!path.empty()) { lldb::user_id_t retcode = - FileSystem::GetFileSize(FileSpec(path.c_str(), false)); + FileSystem::GetFileSize(FileSpec(llvm::StringRef(path.c_str()), false)); StreamString response; response.PutChar('F'); response.PutHex64(retcode); @@ -684,7 +684,8 @@ std::string path; packet.GetHexByteString(path); if (!path.empty()) { - bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false)); + bool retcode = FileSystem::GetFileExists( + FileSpec(llvm::StringRef(path.c_str()), false)); StreamString response; response.PutChar('F'); response.PutChar(','); @@ -776,7 +777,8 @@ if (!path.empty()) { uint64_t a, b; StreamGDBRemote response; - if (!FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b)) { + if (!FileSystem::CalculateMD5( + FileSpec(llvm::StringRef(path.c_str()), false), a, b)) { response.PutCString("F,"); response.PutCString("x"); } else { @@ -936,7 +938,8 @@ return SendOKResponse(); StreamString response; response.PutChar('E'); - response.PutCString(m_process_launch_error.AsCString("")); + response.PutCString( + llvm::StringRef(m_process_launch_error.AsCString(""))); return SendPacketNoLock(response.GetString()); } @@ -1031,8 +1034,8 @@ if (success) { if (arg_idx == 0) - m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), - false); + m_process_launch_info.GetExecutableFile().SetFile( + llvm::StringRef(arg.c_str()), false); m_process_launch_info.GetArguments().AppendArgument(arg); if (log) log->Printf("LLGSPacketHandler::%s added arg %d: \"%s\"", @@ -1276,7 +1279,7 @@ #ifdef __ANDROID__ return HostInfoAndroid::ResolveLibraryPath(module_path, arch); #else - return FileSpec(module_path.c_str(), true); + return FileSpec(llvm::StringRef(module_path.c_str()), true); #endif } @@ -1284,7 +1287,8 @@ const std::string &module_path, const std::string &triple) { ArchSpec arch(triple.c_str()); - const FileSpec req_module_path_spec(module_path.c_str(), true); + const FileSpec req_module_path_spec(llvm::StringRef(module_path.c_str()), + true); const FileSpec module_path_spec = FindModuleFile(req_module_path_spec.GetPath(), arch); const ModuleSpec module_spec(module_path_spec, arch); Index: lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp =================================================================== --- lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp +++ lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp @@ -668,7 +668,7 @@ if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) { response.PutCString("name:"); - response.PutCString(thread_name.c_str()); + response.PutCString(llvm::StringRef(thread_name.c_str())); } else { // The thread name contains special chars, send as hex bytes. response.PutCString("hexname:"); @@ -1529,12 +1529,12 @@ StreamGDBRemote response; response.PutCString("name:"); - response.PutCString(reg_info->name); + response.PutCString(llvm::StringRef(reg_info->name)); response.PutChar(';'); if (reg_info->alt_name && reg_info->alt_name[0]) { response.PutCString("alt-name:"); - response.PutCString(reg_info->alt_name); + response.PutCString(llvm::StringRef(reg_info->alt_name)); response.PutChar(';'); } @@ -1606,7 +1606,7 @@ reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index); if (register_set_name) { response.PutCString("set:"); - response.PutCString(register_set_name); + response.PutCString(llvm::StringRef(register_set_name)); response.PutChar(';'); } Index: lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp =================================================================== --- lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp +++ lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp @@ -537,7 +537,8 @@ const char *domainsocket_dir_env = ::getenv("LLDB_DEBUGSERVER_DOMAINSOCKET_DIR"); if (domainsocket_dir_env != nullptr) - g_domainsocket_dir = FileSpec(domainsocket_dir_env, false); + g_domainsocket_dir = + FileSpec(llvm::StringRef(domainsocket_dir_env), false); else HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, g_domainsocket_dir); }); @@ -552,10 +553,10 @@ (llvm::StringRef(prefix) + ".%%%%%%").str()); FileSpec socket_path_spec(GetDomainSocketDir()); - socket_path_spec.AppendPathComponent(socket_name.c_str()); + socket_path_spec.AppendPathComponent(llvm::StringRef(socket_name.c_str())); llvm::sys::fs::createUniqueFile(socket_path_spec.GetCString(), socket_path); - return FileSpec(socket_path.c_str(), false); + return FileSpec(llvm::StringRef(socket_path.c_str()), false); } void GDBRemoteCommunicationServerPlatform::SetPortOffset(uint16_t port_offset) { Index: lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp =================================================================== --- lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp +++ lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp @@ -822,11 +822,13 @@ if (disable_stdio) { // set to /dev/null unless redirected to a file above if (!stdin_file_spec) - stdin_file_spec.SetFile(FileSystem::DEV_NULL, false); + stdin_file_spec.SetFile(llvm::StringRef(FileSystem::DEV_NULL), false); if (!stdout_file_spec) - stdout_file_spec.SetFile(FileSystem::DEV_NULL, false); + stdout_file_spec.SetFile(llvm::StringRef(FileSystem::DEV_NULL), + false); if (!stderr_file_spec) - stderr_file_spec.SetFile(FileSystem::DEV_NULL, false); + stderr_file_spec.SetFile(llvm::StringRef(FileSystem::DEV_NULL), + false); } else if (platform_sp && platform_sp->IsHost()) { // If the debugserver is local and we aren't disabling STDIO, lets use // a pseudo terminal to instead of relying on the 'O' packets for stdio @@ -834,7 +836,8 @@ // does a lot of output. if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) && pty.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, NULL, 0)) { - FileSpec slave_name{pty.GetSlaveName(NULL, 0), false}; + FileSpec slave_name{llvm::StringRef(pty.GetSlaveName(NULL, 0)), + false}; if (!stdin_file_spec) stdin_file_spec = slave_name; @@ -1038,7 +1041,8 @@ for (size_t idx = 0; idx < num_cmds; idx++) { StringExtractorGDBRemote response; m_gdb_comm.SendPacketAndWaitForResponse( - GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false); + llvm::StringRef(GetExtraStartupCommands().GetArgumentAtIndex(idx)), + response, false); } return error; } @@ -4577,7 +4581,7 @@ if (!modInfo.get_link_map(link_map)) link_map = LLDB_INVALID_ADDRESS; - FileSpec file(mod_name.c_str(), true); + FileSpec file(llvm::StringRef(mod_name.c_str()), true); lldb::ModuleSP module_sp = LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset); @@ -4812,7 +4816,7 @@ ParseStructuredDataPacket(llvm::StringRef packet) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); - if (!packet.consume_front(s_async_json_packet_prefix)) { + if (!packet.consume_front(llvm::StringRef(s_async_json_packet_prefix))) { if (log) { log->Printf( "GDBRemoteCommmunicationClientBase::%s() received $J packet " @@ -5029,7 +5033,7 @@ bool send_async = true; StringExtractorGDBRemote response; process->GetGDBRemote().SendPacketAndWaitForResponse( - packet_cstr, response, send_async); + llvm::StringRef(packet_cstr), response, send_async); result.SetStatus(eReturnStatusSuccessFinishResult); Stream &output_strm = result.GetOutputStream(); output_strm.Printf(" packet: %s\n", packet_cstr); Index: lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.cpp =================================================================== --- lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.cpp +++ lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.cpp @@ -949,7 +949,7 @@ PythonFile::PythonFile(File &file, const char *mode) { Reset(file, mode); } PythonFile::PythonFile(const char *path, const char *mode) { - lldb_private::File file(path, GetOptionsFromMode(mode)); + lldb_private::File file(path, GetOptionsFromMode(llvm::StringRef(mode))); Reset(file, mode); } @@ -1021,7 +1021,7 @@ if (mode.empty()) return 0; - return llvm::StringSwitch(mode.str().c_str()) + return llvm::StringSwitch(llvm::StringRef(mode.str().c_str())) .Case("r", File::eOpenOptionRead) .Case("w", File::eOpenOptionWrite) .Case("a", File::eOpenOptionWrite | File::eOpenOptionAppend | Index: lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp =================================================================== --- lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp +++ lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp @@ -391,7 +391,7 @@ if (instructions) { StreamFileSP output_sp(io_handler.GetOutputStreamFile()); if (output_sp) { - output_sp->PutCString(instructions); + output_sp->PutCString(llvm::StringRef(instructions)); output_sp->Flush(); } } @@ -2581,7 +2581,7 @@ lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this(); { - FileSpec target_file(pathname, true); + FileSpec target_file(llvm::StringRef(pathname), true); std::string basename(target_file.GetFilename().GetCString()); StreamString command_stream; Index: lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp =================================================================== --- lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp +++ lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp @@ -1075,7 +1075,7 @@ const char *enable_options = options_property_sp->GetAsString()->GetCurrentValue(); - Args args(enable_options); + Args args((llvm::StringRef(enable_options))); if (args.GetArgumentCount() > 0) { // Eliminate the initial '--' that would be required to set the // settings that themselves include '-' and/or '--'. @@ -1712,8 +1712,8 @@ // Build up the module list. FileSpecList module_spec_list; - auto module_file_spec = - FileSpec(GetGlobalProperties()->GetLoggingModuleName(), false); + auto module_file_spec = FileSpec( + llvm::StringRef(GetGlobalProperties()->GetLoggingModuleName()), false); module_spec_list.Append(module_file_spec); // We aren't specifying a source file set. @@ -1818,7 +1818,7 @@ // Display the activity chain, from parent-most to child-most // activity, separated by a colon (:). stream.PutCString("activity-chain="); - stream.PutCString(activity_chain.c_str()); + stream.PutCString(llvm::StringRef(activity_chain.c_str())); #else if (GetGlobalProperties()->GetDisplayActivityChain()) { // Display the activity chain, from parent-most to child-most @@ -1850,7 +1850,7 @@ if (header_count > 0) stream.PutChar(','); stream.PutCString("subsystem="); - stream.PutCString(subsystem.c_str()); + stream.PutCString(llvm::StringRef(subsystem.c_str())); ++header_count; } } @@ -1862,14 +1862,14 @@ if (header_count > 0) stream.PutChar(','); stream.PutCString("category="); - stream.PutCString(category.c_str()); + stream.PutCString(llvm::StringRef(category.c_str())); ++header_count; } } stream.PutCString("] "); auto &result = stream.GetString(); - output_stream.PutCString(result.c_str()); + output_stream.PutCString(llvm::StringRef(result.c_str())); return result.size(); } Index: lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp =================================================================== --- lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp +++ lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp @@ -603,7 +603,7 @@ cu->GetAbbreviations()->GetAbbreviationDeclaration(abbrCode); if (abbrevDecl) { - s.PutCString(DW_TAG_value_to_name(abbrevDecl->Tag())); + s.PutCString(llvm::StringRef(DW_TAG_value_to_name(abbrevDecl->Tag()))); s.Printf(" [%u] %c\n", abbrCode, abbrevDecl->HasChildren() ? '*' : ' '); // Dump all data in the .debug_info for the attributes @@ -712,7 +712,7 @@ case DW_AT_language: if (verbose) s.PutCString(" ( "); - s.PutCString(DW_LANG_value_to_name(form_value.Unsigned())); + s.PutCString(llvm::StringRef(DW_LANG_value_to_name(form_value.Unsigned()))); if (verbose) s.PutCString(" )"); break; @@ -720,7 +720,7 @@ case DW_AT_encoding: if (verbose) s.PutCString(" ( "); - s.PutCString(DW_ATE_value_to_name(form_value.Unsigned())); + s.PutCString(llvm::StringRef(DW_ATE_value_to_name(form_value.Unsigned()))); if (verbose) s.PutCString(" )"); break; @@ -1216,7 +1216,7 @@ const char *name = die.GetAttributeValueAsString( dwarf2Data, cu, DW_AT_name, nullptr, true); if (name) { - s.PutCString(name); + s.PutCString(llvm::StringRef(name)); return true; } } @@ -1250,7 +1250,7 @@ } else { const char *name = die.GetPubname(dwarf2Data, cu); if (name) - s.PutCString(name); + s.PutCString(llvm::StringRef(name)); else { bool result = true; const DWARFAbbreviationDeclaration *abbrevDecl = Index: lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp =================================================================== --- lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp +++ lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugLine.cpp @@ -865,19 +865,20 @@ FileSpec &file) const { uint32_t idx = file_idx - 1; // File indexes are 1 based... if (idx < file_names.size()) { - file.SetFile(file_names[idx].name, false); + file.SetFile(llvm::StringRef(file_names[idx].name), false); if (file.IsRelative()) { if (file_names[idx].dir_idx > 0) { const uint32_t dir_idx = file_names[idx].dir_idx - 1; if (dir_idx < include_directories.size()) { - file.PrependPathComponent(include_directories[dir_idx]); + file.PrependPathComponent( + llvm::StringRef(include_directories[dir_idx])); if (!file.IsRelative()) return true; } } if (comp_dir && comp_dir[0]) - file.PrependPathComponent(comp_dir); + file.PrependPathComponent(llvm::StringRef(comp_dir)); } return true; } Index: lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfoEntry.cpp =================================================================== --- lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfoEntry.cpp +++ lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugMacinfoEntry.cpp @@ -35,7 +35,7 @@ void DWARFDebugMacinfoEntry::Dump(Stream *s) const { if (m_type_code) { - s->PutCString(DW_MACINFO_value_to_name(m_type_code)); + s->PutCString(llvm::StringRef(DW_MACINFO_value_to_name(m_type_code))); switch (m_type_code) { case DW_MACINFO_define: Index: lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugPubnamesSet.cpp =================================================================== --- lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugPubnamesSet.cpp +++ lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugPubnamesSet.cpp @@ -140,7 +140,7 @@ DescriptorConstIter pos; DescriptorConstIter end = m_descriptors.end(); for (pos = m_descriptors.begin(); pos != end; ++pos) { - if (regex.Execute(pos->name.c_str())) + if (regex.Execute(llvm::StringRef(pos->name.c_str()))) die_offset_coll.push_back(m_header.die_offset + pos->offset); } } Index: lldb/source/Plugins/SymbolFile/DWARF/HashedNameToDIE.cpp =================================================================== --- lldb/source/Plugins/SymbolFile/DWARF/HashedNameToDIE.cpp +++ lldb/source/Plugins/SymbolFile/DWARF/HashedNameToDIE.cpp @@ -323,7 +323,7 @@ { const char *tag_cstr = lldb_private::DW_TAG_value_to_name(hash_data.tag); if (tag_cstr) - strm.PutCString(tag_cstr); + strm.PutCString(llvm::StringRef(tag_cstr)); else strm.Printf("DW_TAG_(0x%4.4x)", hash_data.tag); } break; Index: lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp =================================================================== --- lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp +++ lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp @@ -181,7 +181,7 @@ return nullptr; bool is_symlink = false; - FileSpec local_path_spec(local_path, false); + FileSpec local_path_spec(llvm::StringRef(local_path), false); const auto &file_specs = GetGlobalPluginProperties()->GetSymLinkPaths(); for (size_t i = 0; i < file_specs.GetSize() && !is_symlink; ++i) is_symlink = FileSpec::Equal(file_specs.GetFileSpecAtIndex(i), @@ -733,7 +733,7 @@ if (module_sp) { const DWARFDIE cu_die = dwarf_cu->GetCompileUnitDIEOnly(); if (cu_die) { - FileSpec cu_file_spec{cu_die.GetName(), false}; + FileSpec cu_file_spec{llvm::StringRef(cu_die.GetName()), false}; if (cu_file_spec) { // If we have a full path to the compile unit, we don't need to // resolve @@ -742,7 +742,8 @@ if (cu_file_spec.IsRelative()) { const char *cu_comp_dir{ cu_die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr)}; - cu_file_spec.PrependPathComponent(resolveCompDir(cu_comp_dir)); + cu_file_spec.PrependPathComponent( + llvm::StringRef(resolveCompDir(cu_comp_dir))); } std::string remapped_file; @@ -1531,15 +1532,15 @@ if (!dwo_name) return nullptr; - FileSpec dwo_file(dwo_name, true); + FileSpec dwo_file(llvm::StringRef(dwo_name), true); if (dwo_file.IsRelative()) { const char *comp_dir = cu_die.GetAttributeValueAsString( this, &dwarf_cu, DW_AT_comp_dir, nullptr); if (!comp_dir) return nullptr; - dwo_file.SetFile(comp_dir, true); - dwo_file.AppendPathComponent(dwo_name); + dwo_file.SetFile(llvm::StringRef(comp_dir), true); + dwo_file.AppendPathComponent(llvm::StringRef(dwo_name)); } if (!dwo_file.Exists()) @@ -1581,13 +1582,16 @@ die.GetAttributeValueAsString(DW_AT_GNU_dwo_name, nullptr); if (dwo_path) { ModuleSpec dwo_module_spec; - dwo_module_spec.GetFileSpec().SetFile(dwo_path, false); + dwo_module_spec.GetFileSpec().SetFile(llvm::StringRef(dwo_path), + false); if (dwo_module_spec.GetFileSpec().IsRelative()) { const char *comp_dir = die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr); if (comp_dir) { - dwo_module_spec.GetFileSpec().SetFile(comp_dir, true); - dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path); + dwo_module_spec.GetFileSpec().SetFile(llvm::StringRef(comp_dir), + true); + dwo_module_spec.GetFileSpec().AppendPathComponent( + llvm::StringRef(dwo_path)); } } dwo_module_spec.GetArchitecture() = @@ -2113,7 +2117,7 @@ if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context, basename)) - basename = name_cstr; + basename = llvm::StringRef(name_cstr); m_apple_names_ap->FindByName(basename.data(), die_offsets); } Index: lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp =================================================================== --- lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp +++ lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.cpp @@ -352,7 +352,7 @@ so_symbol->GetType() == eSymbolTypeSourceFile && oso_symbol->GetType() == eSymbolTypeObjectFile) { m_compile_unit_infos[i].so_file.SetFile( - so_symbol->GetName().AsCString(), false); + llvm::StringRef(so_symbol->GetName().AsCString()), false); m_compile_unit_infos[i].oso_path = oso_symbol->GetName(); TimeValue oso_mod_time; oso_mod_time.OffsetWithSeconds(oso_symbol->GetIntegerValue(0)); @@ -421,7 +421,7 @@ comp_unit_info->oso_sp.reset(new OSOInfo()); m_oso_map[comp_unit_info->oso_path] = comp_unit_info->oso_sp; const char *oso_path = comp_unit_info->oso_path.GetCString(); - FileSpec oso_file(oso_path, false); + FileSpec oso_file(llvm::StringRef(oso_path), false); ConstString oso_object; if (oso_file.Exists()) { TimeValue oso_mod_time(oso_file.GetModificationTime()); Index: lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp =================================================================== --- lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp +++ lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp @@ -470,8 +470,9 @@ lldb_private::TypeMap &types) { auto global = m_session_up->getGlobalScope(); std::unique_ptr results; - results = global->findChildren(PDB_SymType::None, name.c_str(), - PDB_NameSearchFlags::NS_Default); + results = + global->findChildren(PDB_SymType::None, llvm::StringRef(name.c_str()), + PDB_NameSearchFlags::NS_Default); uint32_t matches = 0; Index: lldb/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.cpp =================================================================== --- lldb/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.cpp +++ lldb/source/Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.cpp @@ -182,8 +182,8 @@ if (!DBGBuildSourcePath.empty() && !DBGSourcePath.empty()) { if (DBGSourcePath[0] == '~') { - FileSpec resolved_source_path(DBGSourcePath.c_str(), - true); + FileSpec resolved_source_path( + llvm::StringRef(DBGSourcePath.c_str()), true); DBGSourcePath = resolved_source_path.GetPath(); } module_sp->GetSourceMappingList().Append( @@ -246,7 +246,8 @@ } if (DBGSourcePath[0] == '~') { FileSpec resolved_source_path( - DBGSourcePath.c_str(), true); + llvm::StringRef(DBGSourcePath.c_str()), + true); DBGSourcePath = resolved_source_path.GetPath(); } Index: lldb/source/Symbol/ClangASTContext.cpp =================================================================== --- lldb/source/Symbol/ClangASTContext.cpp +++ lldb/source/Symbol/ClangASTContext.cpp @@ -1387,7 +1387,8 @@ CXXRecordDecl *decl = CXXRecordDecl::Create( *ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(), - SourceLocation(), is_anonymous ? nullptr : &ast->Idents.get(name)); + SourceLocation(), + is_anonymous ? nullptr : &ast->Idents.get(llvm::StringRef(name))); if (is_anonymous) decl->setAnonymousStructOrUnion(true); @@ -1420,7 +1421,7 @@ IdentifierInfo *identifier_info = nullptr; if (name && name[0]) - identifier_info = &ast->Idents.get(name); + identifier_info = &ast->Idents.get(llvm::StringRef(name)); if (template_param_infos.args[i].getKind() == TemplateArgument::Integral) { template_param_decls.push_back(NonTypeTemplateParmDecl::Create( *ast, @@ -1487,7 +1488,8 @@ if (decl_ctx == nullptr) decl_ctx = ast->getTranslationUnitDecl(); - IdentifierInfo &identifier_info = ast->Idents.get(class_name); + IdentifierInfo &identifier_info = + ast->Idents.get(llvm::StringRef(class_name)); DeclarationName decl_name(&identifier_info); clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name); @@ -1690,8 +1692,8 @@ decl_ctx = ast->getTranslationUnitDecl(); ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create( - *ast, decl_ctx, SourceLocation(), &ast->Idents.get(name), nullptr, - nullptr, SourceLocation(), + *ast, decl_ctx, SourceLocation(), &ast->Idents.get(llvm::StringRef(name)), + nullptr, nullptr, SourceLocation(), /*isForwardDecl,*/ isInternal); @@ -1741,7 +1743,7 @@ decl_ctx = translation_unit_decl; if (name) { - IdentifierInfo &identifier_info = ast->Idents.get(name); + IdentifierInfo &identifier_info = ast->Idents.get(llvm::StringRef(name)); DeclarationName decl_name(&identifier_info); clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name); for (NamedDecl *decl : result) { @@ -1867,8 +1869,9 @@ clang::VarDecl *var_decl = clang::VarDecl::Create( *getASTContext(), decl_context, clang::SourceLocation(), clang::SourceLocation(), - name && name[0] ? &getASTContext()->Idents.getOwn(name) : nullptr, type, - nullptr, clang::SC_None); + name && name[0] ? &getASTContext()->Idents.getOwn(llvm::StringRef(name)) + : nullptr, + type, nullptr, clang::SC_None); var_decl->setAccess(clang::AS_public); decl_context->addDecl(var_decl); return var_decl; @@ -1958,7 +1961,7 @@ clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS; if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS) return DeclarationName(&getASTContext()->Idents.get( - name)); // Not operator, but a regular function. + llvm::StringRef(name))); // Not operator, but a regular function. // Check the number of operator parameters. Sometimes we have // seen bad DWARF that doesn't correctly describe operators and @@ -2052,11 +2055,11 @@ const char *name, const CompilerType ¶m_type, int storage) { ASTContext *ast = getASTContext(); assert(ast != nullptr); - return ParmVarDecl::Create(*ast, ast->getTranslationUnitDecl(), - SourceLocation(), SourceLocation(), - name && name[0] ? &ast->Idents.get(name) : nullptr, - ClangUtil::GetQualType(param_type), nullptr, - (clang::StorageClass)storage, nullptr); + return ParmVarDecl::Create( + *ast, ast->getTranslationUnitDecl(), SourceLocation(), SourceLocation(), + name && name[0] ? &ast->Idents.get(llvm::StringRef(name)) : nullptr, + ClangUtil::GetQualType(param_type), nullptr, (clang::StorageClass)storage, + nullptr); } void ClangASTContext::SetFunctionParameters(FunctionDecl *function_decl, @@ -2158,7 +2161,8 @@ EnumDecl *enum_decl = EnumDecl::Create( *ast, decl_ctx, SourceLocation(), SourceLocation(), - name && name[0] ? &ast->Idents.get(name) : nullptr, nullptr, + name && name[0] ? &ast->Idents.get(llvm::StringRef(name)) : nullptr, + nullptr, false, // IsScoped false, // IsScopedUsingClassTag false); // IsFixed @@ -4699,7 +4703,7 @@ clang::TypedefDecl *decl = clang::TypedefDecl::Create( *clang_ast, decl_ctx, clang::SourceLocation(), clang::SourceLocation(), - &clang_ast->Idents.get(typedef_name), + &clang_ast->Idents.get(llvm::StringRef(typedef_name)), clang_ast->getTrivialTypeSourceInfo(qual_type)); decl->setAccess(clang::AS_public); // TODO respect proper access specifier @@ -4805,7 +4809,7 @@ clang::TypedefDecl *decl = clang::TypedefDecl::Create( *clang_ast, decl_ctx, clang::SourceLocation(), clang::SourceLocation(), - &clang_ast->Idents.get(typedef_name), + &clang_ast->Idents.get(llvm::StringRef(typedef_name)), clang_ast->getTrivialTypeSourceInfo(qual_type)); clang::TagDecl *tdecl = nullptr; @@ -7678,12 +7682,13 @@ field = clang::FieldDecl::Create( *clang_ast, record_decl, clang::SourceLocation(), clang::SourceLocation(), - name ? &clang_ast->Idents.get(name) : nullptr, // Identifier - ClangUtil::GetQualType(field_clang_type), // Field type - nullptr, // TInfo * - bit_width, // BitWidth - false, // Mutable - clang::ICIS_NoInit); // HasInit + name ? &clang_ast->Idents.get(llvm::StringRef(name)) + : nullptr, // Identifier + ClangUtil::GetQualType(field_clang_type), // Field type + nullptr, // TInfo * + bit_width, // BitWidth + false, // Mutable + clang::ICIS_NoInit); // HasInit if (!name) { // Determine whether this field corresponds to an anonymous @@ -7721,11 +7726,12 @@ field = clang::ObjCIvarDecl::Create( *clang_ast, class_interface_decl, clang::SourceLocation(), clang::SourceLocation(), - name ? &clang_ast->Idents.get(name) : nullptr, // Identifier - ClangUtil::GetQualType(field_clang_type), // Field type - nullptr, // TypeSourceInfo * - ConvertAccessTypeToObjCIvarAccessControl(access), bit_width, - is_synthesized); + name ? &clang_ast->Idents.get(llvm::StringRef(name)) + : nullptr, // Identifier + ClangUtil::GetQualType(field_clang_type), // Field type + nullptr, // TypeSourceInfo * + ConvertAccessTypeToObjCIvarAccessControl(access), + bit_width, is_synthesized); if (field) { class_interface_decl->addDecl(field); @@ -7879,7 +7885,7 @@ record_decl, // DeclContext * clang::SourceLocation(), // clang::SourceLocation StartLoc clang::SourceLocation(), // clang::SourceLocation IdLoc - name ? &ast->getASTContext()->Idents.get(name) + name ? &ast->getASTContext()->Idents.get(llvm::StringRef(name)) : nullptr, // clang::IdentifierInfo * ClangUtil::GetQualType(var_type), // Variable clang::QualType nullptr, // TypeSourceInfo * @@ -7918,7 +7924,8 @@ clang::CXXMethodDecl *cxx_method_decl = nullptr; - clang::DeclarationName decl_name(&getASTContext()->Idents.get(name)); + clang::DeclarationName decl_name( + &getASTContext()->Idents.get(llvm::StringRef(name))); const clang::FunctionType *function_type = llvm::dyn_cast(method_qual_type.getTypePtr()); @@ -8186,7 +8193,7 @@ clang::ObjCPropertyDecl *property_decl = clang::ObjCPropertyDecl::Create( *clang_ast, class_interface_decl, clang::SourceLocation(), // Source Location - &clang_ast->Idents.get(property_name), + &clang_ast->Idents.get(llvm::StringRef(property_name)), clang::SourceLocation(), // Source Location for AT clang::SourceLocation(), // Source location for ( ivar_decl ? ivar_decl->getType() @@ -8204,15 +8211,15 @@ if (property_setter_name != nullptr) { std::string property_setter_no_colon( property_setter_name, strlen(property_setter_name) - 1); - clang::IdentifierInfo *setter_ident = - &clang_ast->Idents.get(property_setter_no_colon.c_str()); + clang::IdentifierInfo *setter_ident = &clang_ast->Idents.get( + llvm::StringRef(property_setter_no_colon.c_str())); setter_sel = clang_ast->Selectors.getSelector(1, &setter_ident); } else if (!(property_attributes & DW_APPLE_PROPERTY_readonly)) { std::string setter_sel_string("set"); setter_sel_string.push_back(::toupper(property_name[0])); setter_sel_string.append(&property_name[1]); - clang::IdentifierInfo *setter_ident = - &clang_ast->Idents.get(setter_sel_string.c_str()); + clang::IdentifierInfo *setter_ident = &clang_ast->Idents.get( + llvm::StringRef(setter_sel_string.c_str())); setter_sel = clang_ast->Selectors.getSelector(1, &setter_ident); } property_decl->setSetterName(setter_sel); @@ -8221,11 +8228,11 @@ if (property_getter_name != nullptr) { clang::IdentifierInfo *getter_ident = - &clang_ast->Idents.get(property_getter_name); + &clang_ast->Idents.get(llvm::StringRef(property_getter_name)); getter_sel = clang_ast->Selectors.getSelector(0, &getter_ident); } else { clang::IdentifierInfo *getter_ident = - &clang_ast->Idents.get(property_name); + &clang_ast->Idents.get(llvm::StringRef(property_name)); getter_sel = clang_ast->Selectors.getSelector(0, &getter_ident); } property_decl->setGetterName(getter_sel); @@ -8729,7 +8736,7 @@ clang::EnumConstantDecl *enumerator_decl = clang::EnumConstantDecl::Create( *getASTContext(), enutype->getDecl(), clang::SourceLocation(), - name ? &getASTContext()->Idents.get(name) + name ? &getASTContext()->Idents.get(llvm::StringRef(name)) : nullptr, // Identifier ClangUtil::GetQualType(enumerator_clang_type), nullptr, enum_llvm_apsint); @@ -9254,7 +9261,8 @@ enum_end_pos = enum_decl->enumerator_end(); enum_pos != enum_end_pos; ++enum_pos) { if (enum_pos->getInitVal().getSExtValue() == enum_svalue) { - s->PutCString(enum_pos->getNameAsString().c_str()); + s->PutCString( + llvm::StringRef(enum_pos->getNameAsString().c_str())); return true; } } @@ -9268,7 +9276,8 @@ enum_end_pos = enum_decl->enumerator_end(); enum_pos != enum_end_pos; ++enum_pos) { if (enum_pos->getInitVal().getZExtValue() == enum_uvalue) { - s->PutCString(enum_pos->getNameAsString().c_str()); + s->PutCString( + llvm::StringRef(enum_pos->getNameAsString().c_str())); return true; } } @@ -9438,7 +9447,7 @@ typedef_decl->getQualifiedNameAsString()); if (!clang_typedef_name.empty()) { s->PutCString("typedef "); - s->PutCString(clang_typedef_name.c_str()); + s->PutCString(llvm::StringRef(clang_typedef_name.c_str())); } } } break; @@ -9488,7 +9497,7 @@ } else { std::string clang_type_name(qual_type.getAsString()); if (!clang_type_name.empty()) - s->PutCString(clang_type_name.c_str()); + s->PutCString(llvm::StringRef(clang_type_name.c_str())); } } } @@ -9769,14 +9778,16 @@ llvm::dyn_cast(target)) { IdentifierInfo *ii = nd->getIdentifier(); if (ii != nullptr && - ii->getName().equals(name.AsCString(nullptr))) + ii->getName().equals( + llvm::StringRef(name.AsCString(nullptr)))) found_decls.push_back(CompilerDecl(this, nd)); } } } else if (clang::NamedDecl *nd = llvm::dyn_cast(child)) { IdentifierInfo *ii = nd->getIdentifier(); - if (ii != nullptr && ii->getName().equals(name.AsCString(nullptr))) + if (ii != nullptr && + ii->getName().equals(llvm::StringRef(name.AsCString(nullptr)))) found_decls.push_back(CompilerDecl(this, nd)); } } @@ -9895,7 +9906,8 @@ // Check names. IdentifierInfo *ii = nd->getIdentifier(); if (ii == nullptr || - !ii->getName().equals(child_name->AsCString(nullptr))) + !ii->getName().equals( + llvm::StringRef(child_name->AsCString(nullptr)))) continue; // Check types, if one was provided. if (child_type) { Index: lldb/source/Symbol/CompileUnit.cpp =================================================================== --- lldb/source/Symbol/CompileUnit.cpp +++ lldb/source/Symbol/CompileUnit.cpp @@ -21,10 +21,10 @@ const char *pathname, const lldb::user_id_t cu_sym_id, lldb::LanguageType language, lldb_private::LazyBool is_optimized) - : ModuleChild(module_sp), FileSpec(pathname, false), UserID(cu_sym_id), - m_user_data(user_data), m_language(language), m_flags(0), m_functions(), - m_support_files(), m_line_table_ap(), m_variables(), - m_is_optimized(is_optimized) { + : ModuleChild(module_sp), FileSpec(llvm::StringRef(pathname), false), + UserID(cu_sym_id), m_user_data(user_data), m_language(language), + m_flags(0), m_functions(), m_support_files(), m_line_table_ap(), + m_variables(), m_is_optimized(is_optimized) { if (language != eLanguageTypeUnknown) m_flags.Set(flagsParsedLanguage); assert(module_sp); Index: lldb/source/Symbol/Function.cpp =================================================================== --- lldb/source/Symbol/Function.cpp +++ lldb/source/Symbol/Function.cpp @@ -98,9 +98,9 @@ // s->Indent("[inlined] "); s->Indent(); if (m_mangled) - s->PutCString(m_mangled.GetName(language).AsCString()); + s->PutCString(llvm::StringRef(m_mangled.GetName(language).AsCString())); else - s->PutCString(m_name.AsCString()); + s->PutCString(llvm::StringRef(m_name.AsCString())); } ConstString InlineFunctionInfo::GetName(LanguageType language) const { Index: lldb/source/Symbol/GoASTContext.cpp =================================================================== --- lldb/source/Symbol/GoASTContext.cpp +++ lldb/source/Symbol/GoASTContext.cpp @@ -1021,7 +1021,7 @@ if (s) { for (uint32_t i = 0; i < s->GetNumFields(); ++i) { const GoStruct::Field *f = s->GetField(i); - if (f->m_name.GetStringRef() == name) + if (f->m_name.GetStringRef() == llvm::StringRef(name)) return i; } } else if (t->GetGoKind() == GoType::KIND_PTR || t->IsTypedef()) { @@ -1316,7 +1316,7 @@ } } - s->PutCString(name.AsCString()); + s->PutCString(llvm::StringRef(name.AsCString())); } CompilerType GoASTContext::CreateArrayType(const ConstString &name, Index: lldb/source/Symbol/ObjectFile.cpp =================================================================== --- lldb/source/Symbol/ObjectFile.cpp +++ lldb/source/Symbol/ObjectFile.cpp @@ -582,7 +582,7 @@ std::string obj; if (regex_match.GetMatchAtIndex(path_with_object, 1, path) && regex_match.GetMatchAtIndex(path_with_object, 2, obj)) { - archive_file.SetFile(path.c_str(), false); + archive_file.SetFile(llvm::StringRef(path.c_str()), false); archive_object.SetCString(obj.c_str()); if (must_exist && !archive_file.Exists()) return false; Index: lldb/source/Symbol/Symbol.cpp =================================================================== --- lldb/source/Symbol/Symbol.cpp +++ lldb/source/Symbol/Symbol.cpp @@ -141,7 +141,7 @@ // then make this back into a string that is the re-exported name. intptr_t str_ptr = m_addr_range.GetByteSize(); if (str_ptr != 0) - return FileSpec((const char *)str_ptr, false); + return FileSpec(llvm::StringRef((const char *)str_ptr), false); } return FileSpec(); } Index: lldb/source/Symbol/SymbolContext.cpp =================================================================== --- lldb/source/Symbol/SymbolContext.cpp +++ lldb/source/Symbol/SymbolContext.cpp @@ -843,7 +843,7 @@ break; case eModuleSpecified: { // See if we can find the Module, if so stick it in the SymbolContext. - FileSpec module_file_spec(spec_string, false); + FileSpec module_file_spec(llvm::StringRef(spec_string), false); ModuleSpec module_spec(module_file_spec); lldb::ModuleSP module_sp( m_target_sp->GetImages().FindFirstModule(module_spec)); @@ -858,7 +858,7 @@ // might show up in // a number of CompUnits. Instead we just convert to a FileSpec and store // it away. - m_file_spec_ap.reset(new FileSpec(spec_string, false)); + m_file_spec_ap.reset(new FileSpec(llvm::StringRef(spec_string), false)); m_type |= eFileSpecified; break; case eLineStartSpecified: @@ -913,7 +913,8 @@ if (m_module_sp.get() != sc.module_sp.get()) return false; } else { - FileSpec module_file_spec(m_module_spec.c_str(), false); + FileSpec module_file_spec(llvm::StringRef(m_module_spec.c_str()), + false); if (!FileSpec::Equal(module_file_spec, sc.module_sp->GetFileSpec(), false)) return false; Index: lldb/source/Symbol/Symtab.cpp =================================================================== --- lldb/source/Symbol/Symtab.cpp +++ lldb/source/Symbol/Symtab.cpp @@ -701,7 +701,7 @@ m_symbols[i].GetType() == symbol_type) { const char *name = m_symbols[i].GetName().AsCString(); if (name) { - if (regexp.Execute(name)) + if (regexp.Execute(llvm::StringRef(name))) indexes.push_back(i); } } @@ -726,7 +726,7 @@ const char *name = m_symbols[i].GetName().AsCString(); if (name) { - if (regexp.Execute(name)) + if (regexp.Execute(llvm::StringRef(name))) indexes.push_back(i); } } Index: lldb/source/Symbol/UnwindPlan.cpp =================================================================== --- lldb/source/Symbol/UnwindPlan.cpp +++ lldb/source/Symbol/UnwindPlan.cpp @@ -122,7 +122,7 @@ Thread *thread, uint32_t reg_num) { const RegisterInfo *reg_info = unwind_plan->GetRegisterInfo(thread, reg_num); if (reg_info) - s.PutCString(reg_info->name); + s.PutCString(llvm::StringRef(reg_info->name)); else s.Printf("reg(%u)", reg_num); } Index: lldb/source/Symbol/Variable.cpp =================================================================== --- lldb/source/Symbol/Variable.cpp +++ lldb/source/Symbol/Variable.cpp @@ -84,7 +84,7 @@ return m_mangled.NameMatches(name, language); } bool Variable::NameMatches(const RegularExpression ®ex) const { - if (regex.Execute(m_name.AsCString())) + if (regex.Execute(llvm::StringRef(m_name.AsCString()))) return true; if (m_mangled) return m_mangled.NameMatches(regex, GetLanguage()); Index: lldb/source/Target/FileAction.cpp =================================================================== --- lldb/source/Target/FileAction.cpp +++ lldb/source/Target/FileAction.cpp @@ -29,7 +29,9 @@ m_file_spec.Clear(); } -llvm::StringRef FileAction::GetPath() const { return m_file_spec.GetCString(); } +llvm::StringRef FileAction::GetPath() const { + return llvm::StringRef(m_file_spec.GetCString()); +} const FileSpec &FileAction::GetFileSpec() const { return m_file_spec; } Index: lldb/source/Target/InstrumentationRuntime.cpp =================================================================== --- lldb/source/Target/InstrumentationRuntime.cpp +++ lldb/source/Target/InstrumentationRuntime.cpp @@ -60,7 +60,8 @@ return true; // Keep iterating. const RegularExpression &runtime_regex = GetPatternForRuntimeLibrary(); - if (runtime_regex.Execute(file_spec.GetFilename().GetCString()) || + if (runtime_regex.Execute( + llvm::StringRef(file_spec.GetFilename().GetCString())) || module_sp->IsExecutable()) { if (CheckIfRuntimeIsValid(module_sp)) { SetRuntimeModuleSP(module_sp); Index: lldb/source/Target/Language.cpp =================================================================== --- lldb/source/Target/Language.cpp +++ lldb/source/Target/Language.cpp @@ -173,7 +173,7 @@ LanguageType Language::GetLanguageTypeFromString(llvm::StringRef string) { for (const auto &L : language_names) { - if (string.equals_lower(L.name)) + if (string.equals_lower(llvm::StringRef(L.name))) return static_cast(L.type); } Index: lldb/source/Target/PathMappingList.cpp =================================================================== --- lldb/source/Target/PathMappingList.cpp +++ lldb/source/Target/PathMappingList.cpp @@ -204,8 +204,9 @@ if (orig_path_len >= prefix_len) { if (::strncmp(pos->first.GetCString(), orig_path, prefix_len) == 0) { - new_spec.SetFile(pos->second.GetCString(), false); - new_spec.AppendPathComponent(orig_path + prefix_len); + new_spec.SetFile(llvm::StringRef(pos->second.GetCString()), false); + new_spec.AppendPathComponent( + llvm::StringRef(orig_path + prefix_len)); if (new_spec.Exists()) return true; } Index: lldb/source/Target/Platform.cpp =================================================================== --- lldb/source/Target/Platform.cpp +++ lldb/source/Target/Platform.cpp @@ -92,7 +92,7 @@ if (!llvm::sys::path::home_directory(user_home_dir)) return; - module_cache_dir = FileSpec(user_home_dir.c_str(), false); + module_cache_dir = FileSpec(llvm::StringRef(user_home_dir.c_str()), false); module_cache_dir.AppendPathComponent(".lldb"); module_cache_dir.AppendPathComponent("module_cache"); SetModuleCacheDirectory(module_cache_dir); @@ -573,8 +573,8 @@ FileSpec recurse_dst; recurse_dst.GetDirectory().SetCString(dst_dir.GetPath().c_str()); RecurseCopyBaton rc_baton2 = {recurse_dst, rc_baton->platform_ptr, Error()}; - FileSpec::EnumerateDirectory(src_dir_path.c_str(), true, true, true, - RecurseCopy_Callback, &rc_baton2); + FileSpec::EnumerateDirectory(llvm::StringRef(src_dir_path.c_str()), true, + true, true, RecurseCopy_Callback, &rc_baton2); if (rc_baton2.error.Fail()) { rc_baton->error.SetErrorString(rc_baton2.error.AsCString()); return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out @@ -708,8 +708,9 @@ recurse_dst.GetDirectory().SetCString(fixed_dst.GetCString()); std::string src_dir_path(src.GetPath()); RecurseCopyBaton baton = {recurse_dst, this, Error()}; - FileSpec::EnumerateDirectory(src_dir_path.c_str(), true, true, true, - RecurseCopy_Callback, &baton); + FileSpec::EnumerateDirectory(llvm::StringRef(src_dir_path.c_str()), + true, true, true, RecurseCopy_Callback, + &baton); return baton.error; } } break; @@ -1692,7 +1693,7 @@ FileSpec Platform::GetModuleCacheRoot() { auto dir_spec = GetGlobalPlatformProperties()->GetModuleCacheDirectory(); - dir_spec.AppendPathComponent(GetName().AsCString()); + dir_spec.AppendPathComponent(llvm::StringRef(GetName().AsCString())); return dir_spec; } @@ -1728,7 +1729,8 @@ // Only local file was specified. Install it to the current working // directory. FileSpec target_file = GetWorkingDirectory(); - target_file.AppendPathComponent(local_file.GetFilename().AsCString()); + target_file.AppendPathComponent( + llvm::StringRef(local_file.GetFilename().AsCString())); if (IsRemote() || local_file != target_file) { error = Install(local_file, target_file); if (error.Fail()) Index: lldb/source/Target/Process.cpp =================================================================== --- lldb/source/Target/Process.cpp +++ lldb/source/Target/Process.cpp @@ -400,11 +400,11 @@ for (uint32_t i = 0; i < argc; i++) { if (i > 0) s.PutChar(' '); - s.PutCString(m_arguments.GetArgumentAtIndex(i)); + s.PutCString(llvm::StringRef(m_arguments.GetArgumentAtIndex(i))); } } } else { - s.PutCString(GetName()); + s.PutCString(llvm::StringRef(GetName())); } s.EOL(); @@ -426,7 +426,8 @@ case 'i': // STDIN for read only { FileAction action; - if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false)) + if (action.Open(STDIN_FILENO, FileSpec{llvm::StringRef(option_arg), false}, + true, false)) launch_info.AppendFileAction(action); break; } @@ -434,7 +435,8 @@ case 'o': // Open STDOUT for write only { FileAction action; - if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true)) + if (action.Open(STDOUT_FILENO, FileSpec{llvm::StringRef(option_arg), false}, + false, true)) launch_info.AppendFileAction(action); break; } @@ -442,7 +444,8 @@ case 'e': // STDERR for write only { FileAction action; - if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true)) + if (action.Open(STDERR_FILENO, FileSpec{llvm::StringRef(option_arg), false}, + false, true)) launch_info.AppendFileAction(action); break; } @@ -454,7 +457,7 @@ case 'n': // Disable STDIO { FileAction action; - const FileSpec dev_null{FileSystem::DEV_NULL, false}; + const FileSpec dev_null{llvm::StringRef(FileSystem::DEV_NULL), false}; if (action.Open(STDIN_FILENO, dev_null, true, false)) launch_info.AppendFileAction(action); if (action.Open(STDOUT_FILENO, dev_null, false, true)) @@ -465,7 +468,8 @@ } case 'w': - launch_info.SetWorkingDirectory(FileSpec{option_arg, false}); + launch_info.SetWorkingDirectory( + FileSpec{llvm::StringRef(option_arg), false}); break; case 't': // Open process in new terminal window @@ -511,7 +515,7 @@ case 'c': if (option_arg && option_arg[0]) - launch_info.SetShell(FileSpec(option_arg, false)); + launch_info.SetShell(FileSpec(llvm::StringRef(option_arg), false)); else launch_info.SetShell(HostInfo::GetDefaultShell()); break; @@ -5635,7 +5639,7 @@ if (stop_info_sp) { const char *stop_desc = stop_info_sp->GetDescription(); if (stop_desc) - ts.PutCString(stop_desc); + ts.PutCString(llvm::StringRef(stop_desc)); } ts.Printf(">"); } Index: lldb/source/Target/ProcessInfo.cpp =================================================================== --- lldb/source/Target/ProcessInfo.cpp +++ lldb/source/Target/ProcessInfo.cpp @@ -29,8 +29,9 @@ ProcessInfo::ProcessInfo(const char *name, const ArchSpec &arch, lldb::pid_t pid) - : m_executable(name, false), m_arguments(), m_environment(), - m_uid(UINT32_MAX), m_gid(UINT32_MAX), m_arch(arch), m_pid(pid) {} + : m_executable(llvm::StringRef(name), false), m_arguments(), + m_environment(), m_uid(UINT32_MAX), m_gid(UINT32_MAX), m_arch(arch), + m_pid(pid) {} void ProcessInfo::Clear() { m_executable.Clear(); @@ -101,7 +102,7 @@ // in the launch options. Don't resolve the file path as the path // could be a remote platform path const bool resolve = false; - m_executable.SetFile(first_arg, resolve); + m_executable.SetFile(llvm::StringRef(first_arg), resolve); } } } @@ -118,7 +119,7 @@ // in the launch options. Don't resolve the file path as the path // could be a remote platform path const bool resolve = false; - m_executable.SetFile(first_arg, resolve); + m_executable.SetFile(llvm::StringRef(first_arg), resolve); } } } Index: lldb/source/Target/ProcessLaunchInfo.cpp =================================================================== --- lldb/source/Target/ProcessLaunchInfo.cpp +++ lldb/source/Target/ProcessLaunchInfo.cpp @@ -108,8 +108,9 @@ bool ProcessLaunchInfo::AppendSuppressFileAction(int fd, bool read, bool write) { FileAction file_action; - if (file_action.Open(fd, FileSpec{FileSystem::DEV_NULL, false}, read, - write)) { + if (file_action.Open(fd, + FileSpec{llvm::StringRef(FileSystem::DEV_NULL), false}, + read, write)) { AppendFileAction(file_action); return true; } @@ -304,8 +305,8 @@ open_flags |= O_CLOEXEC; #endif if (m_pty->OpenFirstAvailableMaster(open_flags, nullptr, 0)) { - const FileSpec slave_file_spec{m_pty->GetSlaveName(nullptr, 0), - false}; + const FileSpec slave_file_spec{ + llvm::StringRef(m_pty->GetSlaveName(nullptr, 0)), false}; // Only use the slave tty if we don't have anything specified for // input and don't have an action for stdin @@ -357,7 +358,7 @@ // Add a modified PATH environment variable in case argv[0] // is a relative path. const char *argv0 = argv[0]; - FileSpec arg_spec(argv0, false); + FileSpec arg_spec(llvm::StringRef(argv0), false); if (arg_spec.IsRelative()) { // We have a relative path to our executable which may not work if // we just try to run "a.out" (without it being converted to @@ -384,7 +385,7 @@ new_path += curr_path; } new_path += "\" "; - shell_command.PutCString(new_path.c_str()); + shell_command.PutCString(llvm::StringRef(new_path.c_str())); } if (triple.getOS() != llvm::Triple::Win32 || Index: lldb/source/Target/StackFrame.cpp =================================================================== --- lldb/source/Target/StackFrame.cpp +++ lldb/source/Target/StackFrame.cpp @@ -1745,7 +1745,7 @@ StreamString s; if (frame_marker) - s.PutCString(frame_marker); + s.PutCString(llvm::StringRef(frame_marker)); const FormatEntity::Entry *frame_format = nullptr; Target *target = exe_ctx.GetTargetPtr(); Index: lldb/source/Target/StopInfo.cpp =================================================================== --- lldb/source/Target/StopInfo.cpp +++ lldb/source/Target/StopInfo.cpp @@ -452,7 +452,7 @@ if (log) log->Printf("Error evaluating condition: \"%s\"\n", err_str); - error_sp->PutCString(err_str); + error_sp->PutCString(llvm::StringRef(err_str)); error_sp->EOL(); error_sp->Flush(); } else { @@ -789,7 +789,7 @@ if (log) log->Printf("Error evaluating condition: \"%s\"\n", err_str); - error_sp->PutCString(err_str); + error_sp->PutCString(llvm::StringRef(err_str)); error_sp->EOL(); error_sp->Flush(); // If the condition fails to be parsed or run, we should stop. Index: lldb/source/Target/Target.cpp =================================================================== --- lldb/source/Target/Target.cpp +++ lldb/source/Target/Target.cpp @@ -135,7 +135,8 @@ } else { Module *exe_module = GetExecutableModulePointer(); if (exe_module) - s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString()); + s->PutCString(llvm::StringRef( + exe_module->GetFileSpec().GetFilename().GetCString())); else s->PutCString("No executable module."); } @@ -308,7 +309,7 @@ ConstString remapped_path; if (GetSourcePathMap().ReverseRemapPath(ConstString(file.GetPath().c_str()), remapped_path)) - remapped_file.SetFile(remapped_path.AsCString(), true); + remapped_file.SetFile(llvm::StringRef(remapped_path.AsCString()), true); else remapped_file = file; @@ -932,8 +933,8 @@ file.GetPath().c_str()); return error; } - StructuredData::ObjectSP bkpt_data_sp = - bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey()); + StructuredData::ObjectSP bkpt_data_sp = bkpt_dict->GetValueForKey( + llvm::StringRef(Breakpoint::GetSerializationKey())); if (num_names && !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names)) continue; @@ -2674,8 +2675,8 @@ { // Always install the main executable remote_file = platform_sp->GetRemoteWorkingDirectory(); - remote_file.AppendPathComponent( - module_sp->GetFileSpec().GetFilename().GetCString()); + remote_file.AppendPathComponent(llvm::StringRef( + module_sp->GetFileSpec().GetFilename().GetCString())); } } if (remote_file) { Index: lldb/source/Target/TargetList.cpp =================================================================== --- lldb/source/Target/TargetList.cpp +++ lldb/source/Target/TargetList.cpp @@ -116,7 +116,7 @@ if (user_exe_path && user_exe_path[0]) { ModuleSpecList module_specs; ModuleSpec module_spec; - module_spec.GetFileSpec().SetFile(user_exe_path, true); + module_spec.GetFileSpec().SetFile(llvm::StringRef(user_exe_path), true); // Resolve the executable in case we are given a path to a application // bundle @@ -248,7 +248,8 @@ platform_set.end()) { if (!platform_set.empty()) error_strm.PutCString(", "); - error_strm.PutCString(the_platform_sp->GetName().GetCString()); + error_strm.PutCString( + llvm::StringRef(the_platform_sp->GetName().GetCString())); platform_set.insert(the_platform_sp.get()); } } @@ -341,18 +342,18 @@ if (!arch.IsValid()) arch = specified_arch; - FileSpec file(user_exe_path, false); + FileSpec file(llvm::StringRef(user_exe_path), false); if (!file.Exists() && user_exe_path && user_exe_path[0] == '~') { // we want to expand the tilde but we don't want to resolve any symbolic // links // so we can't use the FileSpec constructor's resolve flag - llvm::SmallString<64> unglobbed_path(user_exe_path); + llvm::SmallString<64> unglobbed_path((llvm::StringRef(user_exe_path))); FileSpec::ResolveUsername(unglobbed_path); if (unglobbed_path.empty()) - file = FileSpec(user_exe_path, false); + file = FileSpec(llvm::StringRef(user_exe_path), false); else - file = FileSpec(unglobbed_path.c_str(), false); + file = FileSpec(llvm::StringRef(unglobbed_path.c_str()), false); } bool user_exe_path_is_bundle = false; @@ -372,7 +373,7 @@ std::string cwd_user_exe_path(cwd); cwd_user_exe_path += '/'; cwd_user_exe_path += user_exe_path; - FileSpec cwd_file(cwd_user_exe_path.c_str(), false); + FileSpec cwd_file(llvm::StringRef(cwd_user_exe_path.c_str()), false); if (cwd_file.Exists()) file = cwd_file; } Index: lldb/source/Target/ThreadPlanCallFunction.cpp =================================================================== --- lldb/source/Target/ThreadPlanCallFunction.cpp +++ lldb/source/Target/ThreadPlanCallFunction.cpp @@ -257,7 +257,7 @@ if (!m_valid) { if (error) { if (m_constructor_errors.GetSize() > 0) - error->PutCString(m_constructor_errors.GetData()); + error->PutCString(llvm::StringRef(m_constructor_errors.GetData())); else error->PutCString("Unknown error"); } Index: lldb/source/Target/ThreadPlanStepInRange.cpp =================================================================== --- lldb/source/Target/ThreadPlanStepInRange.cpp +++ lldb/source/Target/ThreadPlanStepInRange.cpp @@ -354,8 +354,8 @@ RegularExpression::Match regex_match(num_matches); - bool return_value = - avoid_regexp_to_use->Execute(frame_function_name, ®ex_match); + bool return_value = avoid_regexp_to_use->Execute( + llvm::StringRef(frame_function_name), ®ex_match); if (return_value) { if (log) { std::string match; Index: lldb/source/Target/ThreadSpec.cpp =================================================================== --- lldb/source/Target/ThreadSpec.cpp +++ lldb/source/Target/ThreadSpec.cpp @@ -47,22 +47,22 @@ std::unique_ptr thread_spec_up(new ThreadSpec()); bool success = spec_dict.GetValueForKeyAsInteger( - GetKey(OptionNames::ThreadIndex), index); + llvm::StringRef(GetKey(OptionNames::ThreadIndex)), index); if (success) thread_spec_up->SetIndex(index); - success = - spec_dict.GetValueForKeyAsInteger(GetKey(OptionNames::ThreadID), tid); + success = spec_dict.GetValueForKeyAsInteger( + llvm::StringRef(GetKey(OptionNames::ThreadID)), tid); if (success) thread_spec_up->SetTID(tid); - success = - spec_dict.GetValueForKeyAsString(GetKey(OptionNames::ThreadName), name); + success = spec_dict.GetValueForKeyAsString( + llvm::StringRef(GetKey(OptionNames::ThreadName)), name); if (success) thread_spec_up->SetName(name.c_str()); - success = spec_dict.GetValueForKeyAsString(GetKey(OptionNames::ThreadName), - queue_name); + success = spec_dict.GetValueForKeyAsString( + llvm::StringRef(GetKey(OptionNames::ThreadName)), queue_name); if (success) thread_spec_up->SetQueueName(queue_name.c_str()); @@ -73,13 +73,17 @@ StructuredData::DictionarySP data_dict_sp(new StructuredData::Dictionary()); if (m_index != UINT32_MAX) - data_dict_sp->AddIntegerItem(GetKey(OptionNames::ThreadIndex), m_index); + data_dict_sp->AddIntegerItem( + llvm::StringRef(GetKey(OptionNames::ThreadIndex)), m_index); if (m_tid != LLDB_INVALID_THREAD_ID) - data_dict_sp->AddIntegerItem(GetKey(OptionNames::ThreadID), m_tid); + data_dict_sp->AddIntegerItem(llvm::StringRef(GetKey(OptionNames::ThreadID)), + m_tid); if (!m_name.empty()) - data_dict_sp->AddStringItem(GetKey(OptionNames::ThreadName), m_name); + data_dict_sp->AddStringItem( + llvm::StringRef(GetKey(OptionNames::ThreadName)), m_name); if (!m_queue_name.empty()) - data_dict_sp->AddStringItem(GetKey(OptionNames::QueueName), m_queue_name); + data_dict_sp->AddStringItem(llvm::StringRef(GetKey(OptionNames::QueueName)), + m_queue_name); return data_dict_sp; } Index: lldb/source/Utility/ModuleCache.cpp =================================================================== --- lldb/source/Utility/ModuleCache.cpp +++ lldb/source/Utility/ModuleCache.cpp @@ -59,7 +59,7 @@ FileSpec JoinPath(const FileSpec &path1, const char *path2) { FileSpec result_spec(path1); - result_spec.AppendPathComponent(path2); + result_spec.AppendPathComponent(llvm::StringRef(path2)); return result_spec; } @@ -80,8 +80,9 @@ } FileSpec GetSymbolFileSpec(const FileSpec &module_file_spec) { - return FileSpec((module_file_spec.GetPath() + kSymFileExtension).c_str(), - false); + return FileSpec( + llvm::StringRef((module_file_spec.GetPath() + kSymFileExtension).c_str()), + false); } void DeleteExistingModule(const FileSpec &root_dir_spec, @@ -145,8 +146,9 @@ DecrementRefExistingModule(root_dir_spec, sysroot_module_path_spec); } - const auto error = MakeDirectory( - FileSpec(sysroot_module_path_spec.GetDirectory().AsCString(), false)); + const auto error = MakeDirectory(FileSpec( + llvm::StringRef(sysroot_module_path_spec.GetDirectory().AsCString()), + false)); if (error.Fail()) return error; Index: lldb/tools/lldb-mi/MICmdCmdData.cpp =================================================================== --- lldb/tools/lldb-mi/MICmdCmdData.cpp +++ lldb/tools/lldb-mi/MICmdCmdData.cpp @@ -1720,8 +1720,8 @@ // First try matching the LineEntry with the column, // then try without the column. - const bool ok = g_lineentry_col_regex.match(input, &match) || - g_lineentry_nocol_regex.match(input, &match); + const bool ok = g_lineentry_col_regex.match(llvm::StringRef(input), &match) || + g_lineentry_nocol_regex.match(llvm::StringRef(input), &match); if (ok) { start = match[1]; end = match[2]; Index: lldb/tools/lldb-mi/MICmdCmdSymbol.cpp =================================================================== --- lldb/tools/lldb-mi/MICmdCmdSymbol.cpp +++ lldb/tools/lldb-mi/MICmdCmdSymbol.cpp @@ -120,7 +120,8 @@ llvm::SmallVector match; - const bool ok = g_lineentry_header_regex.match(input, &match); + const bool ok = + g_lineentry_header_regex.match(llvm::StringRef(input), &match); if (ok) file = match[1]; return ok; @@ -163,8 +164,8 @@ // First try matching the LineEntry with the column, // then try without the column. - const bool ok = g_lineentry_col_regex.match(input, &match) || - g_lineentry_nocol_regex.match(input, &match); + const bool ok = g_lineentry_col_regex.match(llvm::StringRef(input), &match) || + g_lineentry_nocol_regex.match(llvm::StringRef(input), &match); if (ok) { addr = match[1]; file = match[3]; Index: lldb/tools/lldb-server/lldb-gdbserver.cpp =================================================================== --- lldb/tools/lldb-server/lldb-gdbserver.cpp +++ lldb/tools/lldb-server/lldb-gdbserver.cpp @@ -181,8 +181,8 @@ const std::string &socket_id) { Pipe port_name_pipe; // Wait for 10 seconds for pipe to be opened. - auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false, - std::chrono::seconds{10}); + auto error = port_name_pipe.OpenAsWriterWithTimeout( + llvm::StringRef(named_pipe_path), false, std::chrono::seconds{10}); if (error.Fail()) return error; return writeSocketIdToPipe(port_name_pipe, socket_id); Index: lldb/tools/lldb-server/lldb-platform.cpp =================================================================== --- lldb/tools/lldb-server/lldb-platform.cpp +++ lldb/tools/lldb-server/lldb-platform.cpp @@ -101,7 +101,8 @@ static Error save_socket_id_to_file(const std::string &socket_id, const FileSpec &file_spec) { - FileSpec temp_file_spec(file_spec.GetDirectory().AsCString(), false); + FileSpec temp_file_spec(llvm::StringRef(file_spec.GetDirectory().AsCString()), + false); auto error = FileSystem::MakeDirectory(temp_file_spec, eFilePermissionsDirectoryDefault); if (error.Fail()) @@ -194,7 +195,7 @@ case 'f': // Socket file if (optarg && optarg[0]) - socket_file.SetFile(optarg, false); + socket_file.SetFile(llvm::StringRef(optarg), false); break; case 'p': { Index: lldb/unittests/Host/SocketTest.cpp =================================================================== --- lldb/unittests/Host/SocketTest.cpp +++ lldb/unittests/Host/SocketTest.cpp @@ -51,7 +51,7 @@ const char *listen_remote_address, bool child_processes_inherit, Socket **accept_socket, Error *error) { - *error = listen_socket->Accept(listen_remote_address, + *error = listen_socket->Accept(llvm::StringRef(listen_remote_address), child_processes_inherit, *accept_socket); } @@ -65,7 +65,7 @@ std::unique_ptr listen_socket_up( new SocketType(child_processes_inherit, error)); EXPECT_FALSE(error.Fail()); - error = listen_socket_up->Listen(listen_remote_address, 5); + error = listen_socket_up->Listen(llvm::StringRef(listen_remote_address), 5); EXPECT_FALSE(error.Fail()); EXPECT_TRUE(listen_socket_up->IsValid()); @@ -79,7 +79,8 @@ std::unique_ptr connect_socket_up( new SocketType(child_processes_inherit, error)); EXPECT_FALSE(error.Fail()); - error = connect_socket_up->Connect(connect_remote_address.c_str()); + error = connect_socket_up->Connect( + llvm::StringRef(connect_remote_address.c_str())); EXPECT_FALSE(error.Fail()); EXPECT_TRUE(connect_socket_up->IsValid()); Index: lldb/unittests/Interpreter/TestArgs.cpp =================================================================== --- lldb/unittests/Interpreter/TestArgs.cpp +++ lldb/unittests/Interpreter/TestArgs.cpp @@ -120,7 +120,7 @@ TEST(ArgsTest, GetQuotedCommandString) { Args args; const char *str = "process launch -o stdout.txt -- \"a b c\""; - args.SetCommandString(str); + args.SetCommandString(llvm::StringRef(str)); std::string stdstr; ASSERT_TRUE(args.GetQuotedCommandString(stdstr)); @@ -302,7 +302,8 @@ args.AddOrReplaceEnvironmentVariable(envvar_name, llvm::StringRef("")); EXPECT_TRUE(args.ContainsEnvironmentVariable(envvar_name)); - EXPECT_EQ(envvar_name, args.GetArgumentAtIndex(argument_index)); + EXPECT_EQ(envvar_name, + llvm::StringRef(args.GetArgumentAtIndex(argument_index))); } TEST_F(EnvVarFixture, TestReplaceEnvironmentVariableInitialNoValueWithValue) { @@ -316,7 +317,7 @@ std::stringstream stream; stream << envvar_name.str() << '=' << new_value.str(); EXPECT_EQ(llvm::StringRef(stream.str()), - args.GetArgumentAtIndex(argument_index)); + llvm::StringRef(args.GetArgumentAtIndex(argument_index))); } TEST_F(EnvVarFixture, TestReplaceEnvironmentVariableInitialValueWithNoValue) { @@ -325,7 +326,8 @@ args.AddOrReplaceEnvironmentVariable(envvar_name, llvm::StringRef("")); EXPECT_TRUE(args.ContainsEnvironmentVariable(envvar_name)); - EXPECT_EQ(envvar_name, args.GetArgumentAtIndex(argument_index)); + EXPECT_EQ(envvar_name, + llvm::StringRef(args.GetArgumentAtIndex(argument_index))); } TEST_F(EnvVarFixture, TestReplaceEnvironmentVariableInitialValueWithValue) { @@ -339,5 +341,5 @@ std::stringstream stream; stream << envvar_name.str() << '=' << new_value.str(); EXPECT_EQ(llvm::StringRef(stream.str()), - args.GetArgumentAtIndex(argument_index)); + llvm::StringRef(args.GetArgumentAtIndex(argument_index))); } Index: lldb/unittests/Process/gdb-remote/GDBRemoteClientBaseTest.cpp =================================================================== --- lldb/unittests/Process/gdb-remote/GDBRemoteClientBaseTest.cpp +++ lldb/unittests/Process/gdb-remote/GDBRemoteClientBaseTest.cpp @@ -342,7 +342,8 @@ return; // Send async structured data packet, then stop. - ASSERT_EQ(PacketResult::Success, fix.server.SendPacket(stream.GetData())); + ASSERT_EQ(PacketResult::Success, + fix.server.SendPacket(llvm::StringRef(stream.GetData()))); ASSERT_EQ(PacketResult::Success, fix.server.SendPacket("T01")); ASSERT_EQ(eStateStopped, fix.SendCPacket(response)); ASSERT_EQ("T01", response.GetStringRef()); Index: lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp =================================================================== --- lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp +++ lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp @@ -255,7 +255,7 @@ HandlePacket( server, R"(jModulesInfo:[{"file":"/foo/bar.so","triple":"i386-pc-linux"}])", - response); + llvm::StringRef(response)); ASSERT_FALSE(async_result.get().hasValue()) << "response was: " << response; } Index: lldb/unittests/Process/minidump/MinidumpParserTest.cpp =================================================================== --- lldb/unittests/Process/minidump/MinidumpParserTest.cpp +++ lldb/unittests/Process/minidump/MinidumpParserTest.cpp @@ -38,7 +38,8 @@ class MinidumpParserTest : public testing::Test { public: void SetUp() override { - llvm::StringRef dmp_folder = llvm::sys::path::parent_path(TestMainArgv0); + llvm::StringRef dmp_folder = + llvm::sys::path::parent_path(llvm::StringRef(TestMainArgv0)); inputs_folder = dmp_folder; llvm::sys::path::append(inputs_folder, "Inputs"); } @@ -46,7 +47,7 @@ void SetUpData(const char *minidump_filename, size_t load_size = SIZE_MAX) { llvm::SmallString<128> filename = inputs_folder; llvm::sys::path::append(filename, minidump_filename); - FileSpec minidump_file(filename.c_str(), false); + FileSpec minidump_file(llvm::StringRef(filename.c_str()), false); lldb::DataBufferSP data_sp( minidump_file.MemoryMapFileContents(0, load_size)); llvm::Optional optional_parser = Index: lldb/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp =================================================================== --- lldb/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp +++ lldb/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp @@ -520,11 +520,13 @@ auto dict_sp = dict.CreateStructuredDictionary(); EXPECT_EQ(2U, dict_sp->GetSize()); - EXPECT_TRUE(dict_sp->HasKey(string_key0)); - EXPECT_TRUE(dict_sp->HasKey(string_key1)); + EXPECT_TRUE(dict_sp->HasKey(llvm::StringRef(string_key0))); + EXPECT_TRUE(dict_sp->HasKey(llvm::StringRef(string_key1))); - auto string_sp = dict_sp->GetValueForKey(string_key0)->GetAsString(); - auto int_sp = dict_sp->GetValueForKey(string_key1)->GetAsInteger(); + auto string_sp = + dict_sp->GetValueForKey(llvm::StringRef(string_key0))->GetAsString(); + auto int_sp = + dict_sp->GetValueForKey(llvm::StringRef(string_key1))->GetAsInteger(); EXPECT_STREQ(string_value0, string_sp->GetValue().c_str()); EXPECT_EQ(int_value1, long(int_sp->GetValue())); @@ -589,7 +591,7 @@ EXPECT_TRUE(structured_dict_ptr != nullptr); if (structured_dict_ptr) { StructuredData::ObjectSP structured_addr_value_sp = - structured_dict_ptr->GetValueForKey(key_name); + structured_dict_ptr->GetValueForKey(llvm::StringRef(key_name)); EXPECT_TRUE((bool)structured_addr_value_sp); const uint64_t extracted_value = structured_addr_value_sp->GetIntegerValue(123); Index: lldb/unittests/SymbolFile/PDB/SymbolFilePDBTests.cpp =================================================================== --- lldb/unittests/SymbolFile/PDB/SymbolFilePDBTests.cpp +++ lldb/unittests/SymbolFile/PDB/SymbolFilePDBTests.cpp @@ -58,7 +58,8 @@ ClangASTContext::Initialize(); SymbolFilePDB::Initialize(); - llvm::StringRef exe_folder = llvm::sys::path::parent_path(TestMainArgv0); + llvm::StringRef exe_folder = + llvm::sys::path::parent_path(llvm::StringRef(TestMainArgv0)); llvm::SmallString<128> inputs_folder = exe_folder; llvm::sys::path::append(inputs_folder, "Inputs"); @@ -162,7 +163,7 @@ TEST_F(SymbolFilePDBTests, TestAbilitiesForDWARF) { // Test that when we have Dwarf debug info, SymbolFileDWARF is used. - FileSpec fspec(m_dwarf_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_dwarf_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -178,7 +179,7 @@ TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestAbilitiesForPDB)) { // Test that when we have PDB debug info, SymbolFilePDB is used. - FileSpec fspec(m_pdb_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_pdb_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -197,7 +198,7 @@ // Test that attempting to call ResolveSymbolContext with only a basename // finds all full paths // with the same basename - FileSpec fspec(m_pdb_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_pdb_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -217,7 +218,7 @@ // Test that attempting to call ResolveSymbolContext with a full path only // finds the one source // file that matches the full path. - FileSpec fspec(m_pdb_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_pdb_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -242,7 +243,7 @@ // compiled, but only contributes to the combined code of other source files), // a SymbolContext is returned // for each compiland which has line contributions from the requested header. - FileSpec fspec(m_pdb_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_pdb_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -271,7 +272,7 @@ // compiled, but only contributes to the combined code of other source files), // that if check_inlines // is false, no SymbolContexts are returned. - FileSpec fspec(m_pdb_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_pdb_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -293,7 +294,7 @@ // Test that when calling ResolveSymbolContext with a line number of 0, all // line entries from // the specified files are returned. - FileSpec fspec(m_pdb_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_pdb_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -342,7 +343,7 @@ // Test that when calling ResolveSymbolContext with a specific line number, // only line entries // which match the requested line are returned. - FileSpec fspec(m_pdb_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_pdb_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -391,7 +392,7 @@ } TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestSimpleClassTypes)) { - FileSpec fspec(m_types_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_types_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -414,7 +415,7 @@ } TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestNestedClassTypes)) { - FileSpec fspec(m_types_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_types_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -437,7 +438,7 @@ } TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestClassInNamespace)) { - FileSpec fspec(m_types_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_types_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -460,7 +461,7 @@ } TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestEnumTypes)) { - FileSpec fspec(m_types_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_types_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -487,8 +488,9 @@ std::string sizeof_var = "sizeof_"; sizeof_var.append(Enum); - EXPECT_EQ(GetGlobalConstantInteger(session, sizeof_var.c_str()), - enum_type->GetByteSize()); + EXPECT_EQ( + GetGlobalConstantInteger(session, llvm::StringRef(sizeof_var.c_str())), + enum_type->GetByteSize()); } } @@ -507,7 +509,7 @@ } TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestTypedefs)) { - FileSpec fspec(m_types_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_types_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -535,13 +537,13 @@ std::string sizeof_var = "sizeof_"; sizeof_var.append(Typedef); - EXPECT_EQ(GetGlobalConstantInteger(session, sizeof_var.c_str()), + EXPECT_EQ(GetGlobalConstantInteger(session, sizeof_var), typedef_type->GetByteSize()); } } TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestRegexNameMatch)) { - FileSpec fspec(m_types_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_types_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -558,7 +560,7 @@ } TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestMaxMatches)) { - FileSpec fspec(m_types_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_types_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); @@ -585,7 +587,7 @@ } TEST_F(SymbolFilePDBTests, REQUIRES_DIA_SDK(TestNullName)) { - FileSpec fspec(m_types_test_exe.c_str(), false); + FileSpec fspec(llvm::StringRef(m_types_test_exe.c_str()), false); ArchSpec aspec("i686-pc-windows"); lldb::ModuleSP module = std::make_shared(fspec, aspec); Index: lldb/unittests/Utility/ModuleCacheTest.cpp =================================================================== --- lldb/unittests/Utility/ModuleCacheTest.cpp +++ lldb/unittests/Utility/ModuleCacheTest.cpp @@ -59,7 +59,7 @@ } static FileSpec GetSysrootView(FileSpec spec, const char *hostname) { - spec.AppendPathComponent(hostname); + spec.AppendPathComponent(llvm::StringRef(hostname)); spec.AppendPathComponent(dummy_remote_dir); spec.AppendPathComponent(module_name); return spec; @@ -72,7 +72,8 @@ FileSpec tmpdir_spec; HostInfo::GetLLDBPath(lldb::ePathTypeLLDBTempSystemDir, s_cache_dir); - llvm::StringRef exe_folder = llvm::sys::path::parent_path(TestMainArgv0); + llvm::StringRef exe_folder = + llvm::sys::path::parent_path(llvm::StringRef(TestMainArgv0)); s_test_executable = exe_folder; llvm::sys::path::append(s_test_executable, "Inputs", module_name); } Index: llvm/examples/Kaleidoscope/Chapter8/toy.cpp =================================================================== --- llvm/examples/Kaleidoscope/Chapter8/toy.cpp +++ llvm/examples/Kaleidoscope/Chapter8/toy.cpp @@ -1209,14 +1209,14 @@ TargetOptions opt; auto RM = Optional(); - auto TheTargetMachine = - Target->createTargetMachine(TargetTriple, CPU, Features, opt, RM); + auto TheTargetMachine = Target->createTargetMachine( + TargetTriple, llvm::StringRef(CPU), llvm::StringRef(Features), opt, RM); TheModule->setDataLayout(TheTargetMachine->createDataLayout()); auto Filename = "output.o"; std::error_code EC; - raw_fd_ostream dest(Filename, EC, sys::fs::F_None); + raw_fd_ostream dest(llvm::StringRef(Filename), EC, sys::fs::F_None); if (EC) { errs() << "Could not open file: " << EC.message(); Index: llvm/include/llvm/ADT/StringRef.h =================================================================== --- llvm/include/llvm/ADT/StringRef.h +++ llvm/include/llvm/ADT/StringRef.h @@ -66,6 +66,13 @@ return ::memcmp(Lhs,Rhs,Length); } + /// Helper function to get the initial length when initialized from a + /// literal string. + constexpr static unsigned getInitLength(char const *str, + unsigned count = 0) { + return ('\0' == str[0]) ? count : getInitLength(str + 1, count + 1); + } + public: /// @name Constructors /// @{ @@ -77,10 +84,15 @@ /// if (S == nullptr) StringRef(std::nullptr_t) = delete; + /// String literal + template + constexpr StringRef(const char (&Str)[N]) + : Data(Str), Length(getInitLength(Str)) {} + /// Construct a string ref from a cstring. LLVM_ATTRIBUTE_ALWAYS_INLINE - /*implicit*/ StringRef(const char *Str) - : Data(Str), Length(Str ? ::strlen(Str) : 0) {} + explicit StringRef(const char *Str) + : Data(Str), Length(Str ? strlen(Str) : 0) {} /// Construct a string ref from a pointer and length. LLVM_ATTRIBUTE_ALWAYS_INLINE Index: llvm/include/llvm/CodeGen/AsmPrinter.h =================================================================== --- llvm/include/llvm/CodeGen/AsmPrinter.h +++ llvm/include/llvm/CodeGen/AsmPrinter.h @@ -122,9 +122,9 @@ struct HandlerInfo { AsmPrinterHandler *Handler; - const char *TimerName, *TimerGroupName; - HandlerInfo(AsmPrinterHandler *Handler, const char *TimerName, - const char *TimerGroupName) + StringRef TimerName, TimerGroupName; + HandlerInfo(AsmPrinterHandler *Handler, StringRef TimerName, + StringRef TimerGroupName) : Handler(Handler), TimerName(TimerName), TimerGroupName(TimerGroupName) {} }; Index: llvm/include/llvm/CodeGen/CommandFlags.h =================================================================== --- llvm/include/llvm/CodeGen/CommandFlags.h +++ llvm/include/llvm/CodeGen/CommandFlags.h @@ -365,9 +365,9 @@ "target-features", Features); if (DisableFPElim.getNumOccurrences() > 0) - NewAttrs = NewAttrs.addAttribute(Ctx, AttributeSet::FunctionIndex, - "no-frame-pointer-elim", - DisableFPElim ? "true" : "false"); + NewAttrs = NewAttrs.addAttribute( + Ctx, AttributeSet::FunctionIndex, "no-frame-pointer-elim", + StringRef(DisableFPElim ? "true" : "false")); if (DisableTailCalls.getNumOccurrences() > 0) NewAttrs = NewAttrs.addAttribute(Ctx, AttributeSet::FunctionIndex, Index: llvm/include/llvm/CodeGen/MachineFunction.h =================================================================== --- llvm/include/llvm/CodeGen/MachineFunction.h +++ llvm/include/llvm/CodeGen/MachineFunction.h @@ -623,7 +623,7 @@ MachineInstr::mmo_iterator End); /// Allocate a string and populate it with the given external symbol name. - const char *createExternalSymbolName(StringRef Name); + StringRef createExternalSymbolName(StringRef Name); //===--------------------------------------------------------------------===// // Label Manipulation. Index: llvm/include/llvm/CodeGen/PseudoSourceValue.h =================================================================== --- llvm/include/llvm/CodeGen/PseudoSourceValue.h +++ llvm/include/llvm/CodeGen/PseudoSourceValue.h @@ -131,16 +131,16 @@ /// A specialized pseudo source value for holding external symbol values. class ExternalSymbolPseudoSourceValue : public CallEntryPseudoSourceValue { - const char *ES; + StringRef ES; public: - ExternalSymbolPseudoSourceValue(const char *ES); + ExternalSymbolPseudoSourceValue(StringRef ES); static inline bool classof(const PseudoSourceValue *V) { return V->kind() == ExternalSymbolCallEntry; } - const char *getSymbol() const { return ES; } + StringRef getSymbol() const { return ES; } }; /// Manages creation of pseudo source values. @@ -179,7 +179,7 @@ const PseudoSourceValue *getGlobalValueCallEntry(const GlobalValue *GV); - const PseudoSourceValue *getExternalSymbolCallEntry(const char *ES); + const PseudoSourceValue *getExternalSymbolCallEntry(StringRef ES); }; } // end namespace llvm Index: llvm/include/llvm/CodeGen/SelectionDAG.h =================================================================== --- llvm/include/llvm/CodeGen/SelectionDAG.h +++ llvm/include/llvm/CodeGen/SelectionDAG.h @@ -562,9 +562,9 @@ // to provide debug info for the BB at that time, so keep this one around. SDValue getBasicBlock(MachineBasicBlock *MBB); SDValue getBasicBlock(MachineBasicBlock *MBB, SDLoc dl); - SDValue getExternalSymbol(const char *Sym, EVT VT); - SDValue getExternalSymbol(const char *Sym, const SDLoc &dl, EVT VT); - SDValue getTargetExternalSymbol(const char *Sym, EVT VT, + SDValue getExternalSymbol(StringRef Sym, EVT VT); + SDValue getExternalSymbol(StringRef Sym, const SDLoc &dl, EVT VT); + SDValue getTargetExternalSymbol(StringRef Sym, EVT VT, unsigned char TargetFlags = 0); SDValue getMCSymbol(MCSymbol *Sym, EVT VT); Index: llvm/include/llvm/CodeGen/SelectionDAGNodes.h =================================================================== --- llvm/include/llvm/CodeGen/SelectionDAGNodes.h +++ llvm/include/llvm/CodeGen/SelectionDAGNodes.h @@ -1743,17 +1743,17 @@ }; class ExternalSymbolSDNode : public SDNode { - const char *Symbol; + StringRef Symbol; unsigned char TargetFlags; friend class SelectionDAG; - ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned char TF, EVT VT) - : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol, - 0, DebugLoc(), getSDVTList(VT)), Symbol(Sym), TargetFlags(TF) { - } -public: + ExternalSymbolSDNode(bool isTarget, StringRef Sym, unsigned char TF, EVT VT) + : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol, 0, + DebugLoc(), getSDVTList(VT)), + Symbol(Sym), TargetFlags(TF) {} - const char *getSymbol() const { return Symbol; } +public: + StringRef getSymbol() const { return Symbol; } unsigned char getTargetFlags() const { return TargetFlags; } static bool classof(const SDNode *N) { Index: llvm/include/llvm/IR/DiagnosticInfo.h =================================================================== --- llvm/include/llvm/IR/DiagnosticInfo.h +++ llvm/include/llvm/IR/DiagnosticInfo.h @@ -476,7 +476,7 @@ /// Name of the pass that triggers this report. If this matches the /// regular expression given in -Rpass=regexp, then the remark will /// be emitted. - const char *PassName; + StringRef PassName; /// Textual identifier for the remark. Can be used by external tools reading /// the YAML output file for optimization remarks to identify the remark. @@ -625,7 +625,9 @@ static const char *AlwaysPrint; - bool shouldAlwaysPrint() const { return getPassName() == AlwaysPrint; } + bool shouldAlwaysPrint() const { + return getPassName() == StringRef(AlwaysPrint); + } protected: OptimizationRemarkAnalysis(enum DiagnosticKind Kind, const char *PassName, Index: llvm/include/llvm/IR/Intrinsics.h =================================================================== --- llvm/include/llvm/IR/Intrinsics.h +++ llvm/include/llvm/IR/Intrinsics.h @@ -84,8 +84,7 @@ /// and all entries must start with "llvm.". If NameTable contains an exact /// match for Name or a prefix of Name followed by a dot, its index in /// NameTable is returned. Otherwise, -1 is returned. - int lookupLLVMIntrinsicByName(ArrayRef NameTable, - StringRef Name); + int lookupLLVMIntrinsicByName(ArrayRef NameTable, StringRef Name); /// Map a GCC builtin name to an intrinsic ID. ID getIntrinsicForGCCBuiltin(const char *Prefix, StringRef BuiltinName); Index: llvm/include/llvm/IR/LegacyPassNameParser.h =================================================================== --- llvm/include/llvm/IR/LegacyPassNameParser.h +++ llvm/include/llvm/IR/LegacyPassNameParser.h @@ -68,12 +68,12 @@ // void passRegistered(const PassInfo *P) override { if (ignorablePass(P)) return; - if (findOption(P->getPassArgument().data()) != getNumOptions()) { + if (findOption(P->getPassArgument()) != getNumOptions()) { errs() << "Two passes with the same argument (-" << P->getPassArgument() << ") attempted to be registered!\n"; llvm_unreachable(nullptr); } - addLiteralOption(P->getPassArgument().data(), P, P->getPassName().data()); + addLiteralOption(P->getPassArgument(), P, P->getPassName()); } void passEnumerate(const PassInfo *P) override { passRegistered(P); } Index: llvm/include/llvm/Object/ELFObjectFile.h =================================================================== --- llvm/include/llvm/Object/ELFObjectFile.h +++ llvm/include/llvm/Object/ELFObjectFile.h @@ -843,7 +843,7 @@ case ELF::EM_X86_64: return "ELF32-x86-64"; case ELF::EM_ARM: - return (IsLittleEndian ? "ELF32-arm-little" : "ELF32-arm-big"); + return StringRef(IsLittleEndian ? "ELF32-arm-little" : "ELF32-arm-big"); case ELF::EM_AVR: return "ELF32-avr"; case ELF::EM_HEXAGON: @@ -871,7 +871,8 @@ case ELF::EM_X86_64: return "ELF64-x86-64"; case ELF::EM_AARCH64: - return (IsLittleEndian ? "ELF64-aarch64-little" : "ELF64-aarch64-big"); + return StringRef(IsLittleEndian ? "ELF64-aarch64-little" + : "ELF64-aarch64-big"); case ELF::EM_PPC64: return "ELF64-ppc64"; case ELF::EM_S390: @@ -883,9 +884,11 @@ case ELF::EM_WEBASSEMBLY: return "ELF64-wasm"; case ELF::EM_AMDGPU: - return (EF.getHeader()->e_ident[ELF::EI_OSABI] == ELF::ELFOSABI_AMDGPU_HSA - && IsLittleEndian) ? - "ELF64-amdgpu-hsacobj" : "ELF64-amdgpu"; + return StringRef( + (EF.getHeader()->e_ident[ELF::EI_OSABI] == ELF::ELFOSABI_AMDGPU_HSA && + IsLittleEndian) + ? "ELF64-amdgpu-hsacobj" + : "ELF64-amdgpu"); case ELF::EM_BPF: return "ELF64-BPF"; default: Index: llvm/include/llvm/ProfileData/InstrProf.h =================================================================== --- llvm/include/llvm/ProfileData/InstrProf.h +++ llvm/include/llvm/ProfileData/InstrProf.h @@ -40,37 +40,37 @@ /// Return the name of data section containing profile counter variables. inline StringRef getInstrProfCountersSectionName(bool AddSegment) { - return AddSegment ? "__DATA," INSTR_PROF_CNTS_SECT_NAME_STR - : INSTR_PROF_CNTS_SECT_NAME_STR; + return AddSegment ? StringRef("__DATA," INSTR_PROF_CNTS_SECT_NAME_STR) + : StringRef(INSTR_PROF_CNTS_SECT_NAME_STR); } /// Return the name of data section containing names of instrumented /// functions. inline StringRef getInstrProfNameSectionName(bool AddSegment) { - return AddSegment ? "__DATA," INSTR_PROF_NAME_SECT_NAME_STR - : INSTR_PROF_NAME_SECT_NAME_STR; + return AddSegment ? StringRef("__DATA," INSTR_PROF_NAME_SECT_NAME_STR) + : StringRef(INSTR_PROF_NAME_SECT_NAME_STR); } /// Return the name of the data section containing per-function control /// data. inline StringRef getInstrProfDataSectionName(bool AddSegment) { - return AddSegment ? "__DATA," INSTR_PROF_DATA_SECT_NAME_STR - ",regular,live_support" - : INSTR_PROF_DATA_SECT_NAME_STR; + return AddSegment ? StringRef("__DATA," INSTR_PROF_DATA_SECT_NAME_STR + ",regular,live_support") + : StringRef(INSTR_PROF_DATA_SECT_NAME_STR); } /// Return the name of data section containing pointers to value profile /// counters/nodes. inline StringRef getInstrProfValuesSectionName(bool AddSegment) { - return AddSegment ? "__DATA," INSTR_PROF_VALS_SECT_NAME_STR - : INSTR_PROF_VALS_SECT_NAME_STR; + return AddSegment ? StringRef("__DATA," INSTR_PROF_VALS_SECT_NAME_STR) + : StringRef(INSTR_PROF_VALS_SECT_NAME_STR); } /// Return the name of data section containing nodes holdling value /// profiling data. inline StringRef getInstrProfVNodesSectionName(bool AddSegment) { - return AddSegment ? "__DATA," INSTR_PROF_VNODES_SECT_NAME_STR - : INSTR_PROF_VNODES_SECT_NAME_STR; + return AddSegment ? StringRef("__DATA," INSTR_PROF_VNODES_SECT_NAME_STR) + : StringRef(INSTR_PROF_VNODES_SECT_NAME_STR); } /// Return the name profile runtime entry point to do value profiling @@ -82,8 +82,8 @@ /// Return the name of the section containing function coverage mapping /// data. inline StringRef getInstrProfCoverageSectionName(bool AddSegment) { - return AddSegment ? "__DATA," INSTR_PROF_COVMAP_SECT_NAME_STR - : INSTR_PROF_COVMAP_SECT_NAME_STR; + return AddSegment ? StringRef("__DATA," INSTR_PROF_COVMAP_SECT_NAME_STR) + : StringRef(INSTR_PROF_COVMAP_SECT_NAME_STR); } /// Return the name prefix of variables containing instrumented function names. Index: llvm/include/llvm/Support/SourceMgr.h =================================================================== --- llvm/include/llvm/Support/SourceMgr.h +++ llvm/include/llvm/Support/SourceMgr.h @@ -277,6 +277,10 @@ } void print(const char *ProgName, raw_ostream &S, bool ShowColors = true, + bool ShowKindLabel = true) const { + print(StringRef(ProgName), S, ShowColors, ShowKindLabel); + } + void print(StringRef ProgName, raw_ostream &S, bool ShowColors = true, bool ShowKindLabel = true) const; }; Index: llvm/include/llvm/Target/TargetLowering.h =================================================================== --- llvm/include/llvm/Target/TargetLowering.h +++ llvm/include/llvm/Target/TargetLowering.h @@ -1862,12 +1862,12 @@ // /// Rename the default libcall routine name for the specified libcall. - void setLibcallName(RTLIB::Libcall Call, const char *Name) { + void setLibcallName(RTLIB::Libcall Call, StringRef Name) { LibcallRoutineNames[Call] = Name; } /// Get the libcall routine name for the specified libcall. - const char *getLibcallName(RTLIB::Libcall Call) const { + StringRef getLibcallName(RTLIB::Libcall Call) const { return LibcallRoutineNames[Call]; } @@ -2068,7 +2068,7 @@ PromoteToType; /// Stores the name each libcall. - const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL]; + StringRef LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL]; /// The ISD::CondCode that should be used to test the result of each of the /// comparison libcall against zero. Index: llvm/include/llvm/Transforms/Utils/LoopUtils.h =================================================================== --- llvm/include/llvm/Transforms/Utils/LoopUtils.h +++ llvm/include/llvm/Transforms/Utils/LoopUtils.h @@ -458,8 +458,7 @@ StringRef Name); /// \brief Set input string into loop metadata by keeping other values intact. -void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, - unsigned V = 0); +void addStringMetadataToLoop(Loop *TheLoop, StringRef MDString, unsigned V = 0); /// Helper to consistently add the set of standard passes to a loop pass's \c /// AnalysisUsage. Index: llvm/lib/Bitcode/Writer/BitWriter.cpp =================================================================== --- llvm/lib/Bitcode/Writer/BitWriter.cpp +++ llvm/lib/Bitcode/Writer/BitWriter.cpp @@ -19,7 +19,7 @@ int LLVMWriteBitcodeToFile(LLVMModuleRef M, const char *Path) { std::error_code EC; - raw_fd_ostream OS(Path, EC, sys::fs::F_None); + raw_fd_ostream OS(StringRef(Path), EC, sys::fs::F_None); if (EC) return -1; Index: llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp =================================================================== --- llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp +++ llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp @@ -55,10 +55,10 @@ #define DEBUG_TYPE "asm-printer" -static const char *const DWARFGroupName = "DWARF Emission"; -static const char *const DbgTimerName = "Debug Info Emission"; -static const char *const EHTimerName = "DWARF Exception Writer"; -static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables"; +static const char DWARFGroupName[] = "DWARF Emission"; +static const char DbgTimerName[] = "Debug Info Emission"; +static const char EHTimerName[] = "DWARF Exception Writer"; +static const char CodeViewLineTablesGroupName[] = "CodeView Line Tables"; STATISTIC(EmittedInsts, "Number of machine instrs printed"); Index: llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp =================================================================== --- llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp +++ llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp @@ -120,8 +120,8 @@ "Abstract subprograms")), cl::init(DefaultLinkageNames)); -static const char *const DWARFGroupName = "DWARF Emission"; -static const char *const DbgTimerName = "DWARF Debug Writer"; +static const char DWARFGroupName[] = "DWARF Emission"; +static const char DbgTimerName[] = "DWARF Debug Writer"; void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) { BS.EmitInt8( Index: llvm/lib/CodeGen/AsmPrinter/WinException.cpp =================================================================== --- llvm/lib/CodeGen/AsmPrinter/WinException.cpp +++ llvm/lib/CodeGen/AsmPrinter/WinException.cpp @@ -174,7 +174,7 @@ const Function *F = MF->getFunction(); StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName()); MCContext &Ctx = MF->getContext(); - StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch"; + StringRef HandlerPrefix(MBB->isCleanupFuncletEntry() ? "dtor" : "catch"); return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" + Twine(MBB->getNumber()) + "@?0?" + FuncLinkageName + "@4HA"); Index: llvm/lib/CodeGen/DwarfEHPrepare.cpp =================================================================== --- llvm/lib/CodeGen/DwarfEHPrepare.cpp +++ llvm/lib/CodeGen/DwarfEHPrepare.cpp @@ -207,7 +207,7 @@ if (!RewindFunction) { FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), Type::getInt8PtrTy(Ctx), false); - const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME); + auto RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME); RewindFunction = Fn.getParent()->getOrInsertFunction(RewindName, FTy); } Index: llvm/lib/CodeGen/IntrinsicLowering.cpp =================================================================== --- llvm/lib/CodeGen/IntrinsicLowering.cpp +++ llvm/lib/CodeGen/IntrinsicLowering.cpp @@ -25,9 +25,8 @@ using namespace llvm; template -static void EnsureFunctionExists(Module &M, const char *Name, - ArgIt ArgBegin, ArgIt ArgEnd, - Type *RetTy) { +static void EnsureFunctionExists(Module &M, StringRef Name, ArgIt ArgBegin, + ArgIt ArgEnd, Type *RetTy) { // Insert a correctly-typed definition now. std::vector ParamTys; for (ArgIt I = ArgBegin; I != ArgEnd; ++I) @@ -35,9 +34,8 @@ M.getOrInsertFunction(Name, FunctionType::get(RetTy, ParamTys, false)); } -static void EnsureFPIntrinsicsExist(Module &M, Function &Fn, - const char *FName, - const char *DName, const char *LDName) { +static void EnsureFPIntrinsicsExist(Module &M, Function &Fn, StringRef FName, + StringRef DName, StringRef LDName) { // Insert definitions for all the floating point types. switch((int)Fn.arg_begin()->getType()->getTypeID()) { case Type::FloatTyID: @@ -62,9 +60,8 @@ /// when there was already a prototype for the external function, and if that /// prototype doesn't match the arguments we expect to pass in. template -static CallInst *ReplaceCallWith(const char *NewFn, CallInst *CI, - ArgIt ArgBegin, ArgIt ArgEnd, - Type *RetTy) { +static CallInst *ReplaceCallWith(StringRef NewFn, CallInst *CI, ArgIt ArgBegin, + ArgIt ArgEnd, Type *RetTy) { // If we haven't already looked up this function, check to see if the // program already contains a function with this name. Module *M = CI->getModule(); @@ -314,9 +311,8 @@ return LowerCTPOP(Context, V, IP); } -static void ReplaceFPIntrinsicWithCall(CallInst *CI, const char *Fname, - const char *Dname, - const char *LDname) { +static void ReplaceFPIntrinsicWithCall(CallInst *CI, StringRef Fname, + StringRef Dname, StringRef LDname) { CallSite CS(CI); switch (CI->getArgOperand(0)->getType()->getTypeID()) { default: llvm_unreachable("Invalid type in intrinsic"); Index: llvm/lib/CodeGen/MIRParser/MIParser.cpp =================================================================== --- llvm/lib/CodeGen/MIRParser/MIParser.cpp +++ llvm/lib/CodeGen/MIRParser/MIParser.cpp @@ -276,7 +276,7 @@ void MIParser::lex(unsigned SkipChar) { CurrentSource = lexMIToken( - CurrentSource.data() + SkipChar, Token, + CurrentSource.drop_front(SkipChar), Token, [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); }); } @@ -1047,7 +1047,7 @@ const Constant *&C) { auto Source = StringValue.str(); // The source has to be null terminated. SMDiagnostic Err; - C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent(), + C = parseConstantValue(Source, Err, *MF.getFunction()->getParent(), &PFS.IRSlots); if (!C) return error(Loc + Err.getColumnNo(), Err.getMessage()); @@ -1300,9 +1300,9 @@ bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) { assert(Token.is(MIToken::ExternalSymbol)); - const char *Symbol = MF.createExternalSymbolName(Token.stringValue()); + auto Symbol = MF.createExternalSymbolName(Token.stringValue()); lex(); - Dest = MachineOperand::CreateES(Symbol); + Dest = MachineOperand::CreateES(Symbol.data()); if (parseOperandsOffset(Dest)) return true; return false; @@ -1954,7 +1954,7 @@ MachinePointerInfo Ptr = MachinePointerInfo(); if (Token.is(MIToken::Identifier)) { - const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into"; + StringRef Word(Flags & MachineMemOperand::MOLoad ? "from" : "into"); if (Token.stringValue() != Word) return error(Twine("expected '") + Word + "'"); lex(); @@ -2026,7 +2026,7 @@ if (!Names2Regs.empty()) return; // The '%noreg' register is the register 0. - Names2Regs.insert(std::make_pair("noreg", 0)); + Names2Regs.insert(std::make_pair(StringRef("noreg"), 0)); const auto *TRI = MF.getSubtarget().getRegisterInfo(); assert(TRI && "Expected target register info"); for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) { Index: llvm/lib/CodeGen/MIRPrinter.cpp =================================================================== --- llvm/lib/CodeGen/MIRPrinter.cpp +++ llvm/lib/CodeGen/MIRPrinter.cpp @@ -839,7 +839,7 @@ break; case MachineOperand::MO_ExternalSymbol: OS << '$'; - printLLVMNameWithoutPrefix(OS, Op.getSymbolName()); + printLLVMNameWithoutPrefix(OS, StringRef(Op.getSymbolName())); printOffset(Op.getOffset()); break; case MachineOperand::MO_GlobalAddress: Index: llvm/lib/CodeGen/MachineFunction.cpp =================================================================== --- llvm/lib/CodeGen/MachineFunction.cpp +++ llvm/lib/CodeGen/MachineFunction.cpp @@ -396,11 +396,11 @@ return std::make_pair(Result, Result + Num); } -const char *MachineFunction::createExternalSymbolName(StringRef Name) { +StringRef MachineFunction::createExternalSymbolName(StringRef Name) { char *Dest = Allocator.Allocate(Name.size() + 1); std::copy(Name.begin(), Name.end(), Dest); Dest[Name.size()] = 0; - return Dest; + return StringRef(Dest, Name.size()); } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) Index: llvm/lib/CodeGen/PseudoSourceValue.cpp =================================================================== --- llvm/lib/CodeGen/PseudoSourceValue.cpp +++ llvm/lib/CodeGen/PseudoSourceValue.cpp @@ -91,7 +91,7 @@ const GlobalValue *GV) : CallEntryPseudoSourceValue(GlobalValueCallEntry), GV(GV) {} -ExternalSymbolPseudoSourceValue::ExternalSymbolPseudoSourceValue(const char *ES) +ExternalSymbolPseudoSourceValue::ExternalSymbolPseudoSourceValue(StringRef ES) : CallEntryPseudoSourceValue(ExternalSymbolCallEntry), ES(ES) {} PseudoSourceValueManager::PseudoSourceValueManager() @@ -130,7 +130,7 @@ } const PseudoSourceValue * -PseudoSourceValueManager::getExternalSymbolCallEntry(const char *ES) { +PseudoSourceValueManager::getExternalSymbolCallEntry(StringRef ES) { std::unique_ptr &E = ExternalCallEntries[ES]; if (!E) Index: llvm/lib/CodeGen/RegAllocBase.h =================================================================== --- llvm/lib/CodeGen/RegAllocBase.h +++ llvm/lib/CodeGen/RegAllocBase.h @@ -104,7 +104,7 @@ SmallVectorImpl &splitLVRs) = 0; // Use this group name for NamedRegionTimer. - static const char TimerGroupName[]; + static constexpr char TimerGroupName[] = "Register Allocation"; /// Method called when the allocator is about to remove a LiveInterval. virtual void aboutToRemoveInterval(LiveInterval &LI) {} Index: llvm/lib/CodeGen/RegAllocBase.cpp =================================================================== --- llvm/lib/CodeGen/RegAllocBase.cpp +++ llvm/lib/CodeGen/RegAllocBase.cpp @@ -41,7 +41,7 @@ VerifyRegAlloc("verify-regalloc", cl::location(RegAllocBase::VerifyEnabled), cl::desc("Verify during register allocation")); -const char RegAllocBase::TimerGroupName[] = "Register Allocation"; +const char RegAllocBase::TimerGroupName[]; bool RegAllocBase::VerifyEnabled = false; //===----------------------------------------------------------------------===// Index: llvm/lib/CodeGen/RegUsageInfoPropagate.cpp =================================================================== --- llvm/lib/CodeGen/RegUsageInfoPropagate.cpp +++ llvm/lib/CodeGen/RegUsageInfoPropagate.cpp @@ -117,7 +117,7 @@ if (Operand.isGlobal()) UpdateRegMask(cast(Operand.getGlobal())); else if (Operand.isSymbol()) - UpdateRegMask(M->getFunction(Operand.getSymbolName())); + UpdateRegMask(M->getFunction(StringRef(Operand.getSymbolName()))); DEBUG(dbgs() << "Call Instruction After Register Usage Info Propagation : \n"); Index: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp =================================================================== --- llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp +++ llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp @@ -2234,7 +2234,7 @@ case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; } - return TLI.getLibcallName(LC) != nullptr; + return !TLI.getLibcallName(LC).empty(); } /// Issue divrem if both quotient and remainder are needed. Index: llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp =================================================================== --- llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp +++ llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp @@ -429,7 +429,7 @@ Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align); MIB.addConstantPoolIndex(Idx, Offset, CP->getTargetFlags()); } else if (ExternalSymbolSDNode *ES = dyn_cast(Op)) { - MIB.addExternalSymbol(ES->getSymbol(), ES->getTargetFlags()); + MIB.addExternalSymbol(ES->getSymbol().data(), ES->getTargetFlags()); } else if (auto *SymNode = dyn_cast(Op)) { MIB.addSym(SymNode->getMCSymbol()); } else if (BlockAddressSDNode *BA = dyn_cast(Op)) { @@ -950,8 +950,8 @@ // Add the asm string as an external symbol operand. SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString); - const char *AsmStr = cast(AsmStrV)->getSymbol(); - MIB.addExternalSymbol(AsmStr); + auto AsmStr = cast(AsmStrV)->getSymbol(); + MIB.addExternalSymbol(AsmStr.data()); // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore // bits. Index: llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp =================================================================== --- llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp +++ llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp @@ -2143,7 +2143,7 @@ case MVT::f128: LC = RTLIB::SINCOS_F128; break; case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break; } - return TLI.getLibcallName(LC) != nullptr; + return !TLI.getLibcallName(LC).empty(); } /// Return true if sincos libcall is available and can be used to combine sin Index: llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp =================================================================== --- llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp +++ llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp @@ -2431,7 +2431,7 @@ LC = RTLIB::SRA_I128; } - if (LC != RTLIB::UNKNOWN_LIBCALL && TLI.getLibcallName(LC)) { + if (LC != RTLIB::UNKNOWN_LIBCALL && !TLI.getLibcallName(LC).empty()) { SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) }; SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, isSigned, dl).first, Lo, Hi); return; Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp =================================================================== --- llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp +++ llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp @@ -1406,7 +1406,7 @@ return SDValue(N, 0); } -SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { +SDValue SelectionDAG::getExternalSymbol(StringRef Sym, EVT VT) { SDNode *&N = ExternalSymbols[Sym]; if (N) return SDValue(N, 0); N = newSDNode(false, Sym, 0, VT); @@ -1423,7 +1423,7 @@ return SDValue(N, 0); } -SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, +SDValue SelectionDAG::getTargetExternalSymbol(StringRef Sym, EVT VT, unsigned char TargetFlags) { SDNode *&N = TargetExternalSymbols[std::pair(Sym, Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp =================================================================== --- llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp +++ llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp @@ -5484,7 +5484,7 @@ TargetLowering::CallLoweringInfo CLI(DAG); CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee( CallingConv::C, I.getType(), - DAG.getExternalSymbol(TrapFuncName.data(), + DAG.getExternalSymbol(TrapFuncName, TLI.getPointerTy(DAG.getDataLayout())), std::move(Args)); @@ -6409,7 +6409,7 @@ Callee = getValue(I.getCalledValue()); else Callee = DAG.getExternalSymbol( - RenameFn, + StringRef(RenameFn), DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't @@ -6897,7 +6897,7 @@ std::vector AsmNodeOperands; AsmNodeOperands.push_back(SDValue()); // reserve space for input chain AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( - IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); + IA->getAsmString(), TLI.getPointerTy(DAG.getDataLayout()))); // If we have a !srcloc metadata node associated with it, we want to attach // this to the ultimately generated inline asm machineinstr. To do this, we Index: llvm/lib/CodeGen/TargetLoweringBase.cpp =================================================================== --- llvm/lib/CodeGen/TargetLoweringBase.cpp +++ llvm/lib/CodeGen/TargetLoweringBase.cpp @@ -61,7 +61,7 @@ /// InitLibcallNames - Set default libcall names. /// -static void InitLibcallNames(const char **Names, const Triple &TT) { +static void InitLibcallNames(StringRef *Names, const Triple &TT) { Names[RTLIB::SHL_I16] = "__ashlhi3"; Names[RTLIB::SHL_I32] = "__ashlsi3"; Names[RTLIB::SHL_I64] = "__ashldi3"; @@ -832,8 +832,6 @@ MinCmpXchgSizeInBits = 0; - std::fill(std::begin(LibcallRoutineNames), std::end(LibcallRoutineNames), nullptr); - InitLibcallNames(LibcallRoutineNames, TM.getTargetTriple()); InitCmpLibcallCCs(CmpLibcallCCs); InitLibcallCallingConvs(LibcallCallingConvs); @@ -1772,7 +1770,7 @@ // compiler-rt provides a variable with a magic name. Targets that do not // link with compiler-rt may also provide such a variable. Module *M = IRB.GetInsertBlock()->getParent()->getParent(); - const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr"; + StringRef UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr"; auto UnsafeStackPtr = dyn_cast_or_null(M->getNamedValue(UnsafeStackPtrVar)); Index: llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp =================================================================== --- llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp +++ llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp @@ -934,7 +934,7 @@ Selection); } -static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { +static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { if (Kind.isText()) return ".text"; if (Kind.isBSS()) @@ -957,7 +957,7 @@ EmitUniquedSection = TM.getDataSections(); if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) { - const char *Name = getCOFFSectionNameForUniqueGlobal(Kind); + auto Name = getCOFFSectionNameForUniqueGlobal(Kind); unsigned Characteristics = getCOFFSectionFlags(Kind, TM); Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; @@ -1034,7 +1034,7 @@ StringRef COMDATSymName = Sym->getName(); SectionKind Kind = SectionKind::getReadOnly(); - const char *Name = getCOFFSectionNameForUniqueGlobal(Kind); + auto Name = getCOFFSectionNameForUniqueGlobal(Kind); unsigned Characteristics = getCOFFSectionFlags(Kind, TM); Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; unsigned UniqueID = NextUniqueID++; Index: llvm/lib/DebugInfo/DWARF/DWARFFormValue.cpp =================================================================== --- llvm/lib/DebugInfo/DWARF/DWARFFormValue.cpp +++ llvm/lib/DebugInfo/DWARF/DWARFFormValue.cpp @@ -392,7 +392,7 @@ case DW_FORM_data8: OS << format("0x%016" PRIx64, uvalue); break; case DW_FORM_string: OS << '"'; - OS.write_escaped(Value.cstr); + OS.write_escaped(StringRef(Value.cstr)); OS << '"'; break; case DW_FORM_exprloc: @@ -497,7 +497,7 @@ if (DbgStr.hasValue()) { raw_ostream &COS = WithColor(OS, syntax::String); COS << '"'; - COS.write_escaped(DbgStr.getValue()); + COS.write_escaped(StringRef(DbgStr.getValue())); COS << '"'; } } Index: llvm/lib/DebugInfo/Symbolize/DIPrinter.cpp =================================================================== --- llvm/lib/DebugInfo/Symbolize/DIPrinter.cpp +++ llvm/lib/DebugInfo/Symbolize/DIPrinter.cpp @@ -71,8 +71,9 @@ if (FunctionName == kDILineInfoBadString) FunctionName = kBadString; - StringRef Delimiter = PrintPretty ? " at " : "\n"; - StringRef Prefix = (PrintPretty && Inlined) ? " (inlined by) " : ""; + StringRef Delimiter = StringRef(PrintPretty ? " at " : "\n"); + StringRef Prefix = + StringRef((PrintPretty && Inlined) ? " (inlined by) " : ""); OS << Prefix << FunctionName << Delimiter; } std::string Filename = Info.FileName; Index: llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp =================================================================== --- llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp +++ llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp @@ -266,7 +266,7 @@ LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name, LLVMValueRef *OutFn) { - if (Function *F = unwrap(EE)->FindFunctionNamed(Name)) { + if (Function *F = unwrap(EE)->FindFunctionNamed(StringRef(Name))) { *OutFn = wrap(F); return 0; } Index: llvm/lib/ExecutionEngine/Orc/OrcCBindings.cpp =================================================================== --- llvm/lib/ExecutionEngine/Orc/OrcCBindings.cpp +++ llvm/lib/ExecutionEngine/Orc/OrcCBindings.cpp @@ -35,7 +35,7 @@ void LLVMOrcGetMangledSymbol(LLVMOrcJITStackRef JITStack, char **MangledName, const char *SymbolName) { OrcCBindingsStack &J = *unwrap(JITStack); - std::string Mangled = J.mangle(SymbolName); + std::string Mangled = J.mangle(StringRef(SymbolName)); *MangledName = new char[Mangled.size() + 1]; strcpy(*MangledName, Mangled.c_str()); } @@ -54,14 +54,14 @@ const char *StubName, LLVMOrcTargetAddress InitAddr) { OrcCBindingsStack &J = *unwrap(JITStack); - return J.createIndirectStub(StubName, InitAddr); + return J.createIndirectStub(StringRef(StubName), InitAddr); } LLVMOrcErrorCode LLVMOrcSetIndirectStubPointer(LLVMOrcJITStackRef JITStack, const char *StubName, LLVMOrcTargetAddress NewAddr) { OrcCBindingsStack &J = *unwrap(JITStack); - return J.setIndirectStubPointer(StubName, NewAddr); + return J.setIndirectStubPointer(StringRef(StubName), NewAddr); } LLVMOrcModuleHandle Index: llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldChecker.cpp =================================================================== --- llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldChecker.cpp +++ llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldChecker.cpp @@ -152,7 +152,7 @@ std::pair parseBinOpToken(StringRef Expr) const { if (Expr.empty()) - return std::make_pair(BinOpToken::Invalid, ""); + return std::make_pair(BinOpToken::Invalid, StringRef("")); // Handle the two 2-character tokens. if (Expr.startswith("<<")) @@ -220,8 +220,9 @@ // On success, retuns a pair containing the value of the operand, plus // the expression remaining to be evaluated. std::pair evalDecodeOperand(StringRef Expr) const { + StringRef Empty(""); if (!Expr.startswith("(")) - return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), ""); + return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), Empty); StringRef RemainingExpr = Expr.substr(1).ltrim(); StringRef Symbol; std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr); @@ -229,21 +230,21 @@ if (!Checker.isSymbolValid(Symbol)) return std::make_pair( EvalResult(("Cannot decode unknown symbol '" + Symbol + "'").str()), - ""); + Empty); if (!RemainingExpr.startswith(",")) return std::make_pair( - unexpectedToken(RemainingExpr, RemainingExpr, "expected ','"), ""); + unexpectedToken(RemainingExpr, RemainingExpr, "expected ','"), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); EvalResult OpIdxExpr; std::tie(OpIdxExpr, RemainingExpr) = evalNumberExpr(RemainingExpr); if (OpIdxExpr.hasError()) - return std::make_pair(OpIdxExpr, ""); + return std::make_pair(OpIdxExpr, Empty); if (!RemainingExpr.startswith(")")) return std::make_pair( - unexpectedToken(RemainingExpr, RemainingExpr, "expected ')'"), ""); + unexpectedToken(RemainingExpr, RemainingExpr, "expected ')'"), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); MCInst Inst; @@ -251,7 +252,7 @@ if (!decodeInst(Symbol, Inst, Size)) return std::make_pair( EvalResult(("Couldn't decode instruction at '" + Symbol + "'").str()), - ""); + Empty); unsigned OpIdx = OpIdxExpr.getValue(); if (OpIdx >= Inst.getNumOperands()) { @@ -263,7 +264,7 @@ << format("%i", Inst.getNumOperands()) << " operands.\nInstruction is:\n "; Inst.dump_pretty(ErrMsgStream, Checker.InstPrinter); - return std::make_pair(EvalResult(ErrMsgStream.str()), ""); + return std::make_pair(EvalResult(ErrMsgStream.str()), Empty); } const MCOperand &Op = Inst.getOperand(OpIdx); @@ -274,7 +275,7 @@ << Symbol << "' is not an immediate.\nInstruction is:\n "; Inst.dump_pretty(ErrMsgStream, Checker.InstPrinter); - return std::make_pair(EvalResult(ErrMsgStream.str()), ""); + return std::make_pair(EvalResult(ErrMsgStream.str()), Empty); } return std::make_pair(EvalResult(Op.getImm()), RemainingExpr); @@ -288,8 +289,9 @@ // expression remaining to be evaluated. std::pair evalNextPC(StringRef Expr, ParseContext PCtx) const { + StringRef Empty(""); if (!Expr.startswith("(")) - return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), ""); + return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), Empty); StringRef RemainingExpr = Expr.substr(1).ltrim(); StringRef Symbol; std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr); @@ -297,11 +299,11 @@ if (!Checker.isSymbolValid(Symbol)) return std::make_pair( EvalResult(("Cannot decode unknown symbol '" + Symbol + "'").str()), - ""); + Empty); if (!RemainingExpr.startswith(")")) return std::make_pair( - unexpectedToken(RemainingExpr, RemainingExpr, "expected ')'"), ""); + unexpectedToken(RemainingExpr, RemainingExpr, "expected ')'"), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); MCInst Inst; @@ -309,7 +311,7 @@ if (!decodeInst(Symbol, Inst, InstSize)) return std::make_pair( EvalResult(("Couldn't decode instruction at '" + Symbol + "'").str()), - ""); + Empty); uint64_t SymbolAddr = PCtx.IsInsideLoad ? Checker.getSymbolLocalAddr(Symbol) @@ -326,8 +328,9 @@ // remaining to be evaluated. std::pair evalStubAddr(StringRef Expr, ParseContext PCtx) const { + StringRef Empty; if (!Expr.startswith("(")) - return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), ""); + return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), Empty); StringRef RemainingExpr = Expr.substr(1).ltrim(); // Handle file-name specially, as it may contain characters that aren't @@ -339,7 +342,7 @@ if (!RemainingExpr.startswith(",")) return std::make_pair( - unexpectedToken(RemainingExpr, Expr, "expected ','"), ""); + unexpectedToken(RemainingExpr, Expr, "expected ','"), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); StringRef SectionName; @@ -347,7 +350,7 @@ if (!RemainingExpr.startswith(",")) return std::make_pair( - unexpectedToken(RemainingExpr, Expr, "expected ','"), ""); + unexpectedToken(RemainingExpr, Expr, "expected ','"), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); StringRef Symbol; @@ -355,7 +358,7 @@ if (!RemainingExpr.startswith(")")) return std::make_pair( - unexpectedToken(RemainingExpr, Expr, "expected ')'"), ""); + unexpectedToken(RemainingExpr, Expr, "expected ')'"), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); uint64_t StubAddr; @@ -364,15 +367,16 @@ FileName, SectionName, Symbol, PCtx.IsInsideLoad); if (ErrorMsg != "") - return std::make_pair(EvalResult(ErrorMsg), ""); + return std::make_pair(EvalResult(ErrorMsg), Empty); return std::make_pair(EvalResult(StubAddr), RemainingExpr); } std::pair evalSectionAddr(StringRef Expr, ParseContext PCtx) const { + StringRef Empty; if (!Expr.startswith("(")) - return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), ""); + return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), Empty); StringRef RemainingExpr = Expr.substr(1).ltrim(); // Handle file-name specially, as it may contain characters that aren't @@ -384,7 +388,7 @@ if (!RemainingExpr.startswith(",")) return std::make_pair( - unexpectedToken(RemainingExpr, Expr, "expected ','"), ""); + unexpectedToken(RemainingExpr, Expr, "expected ','"), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); StringRef SectionName; @@ -392,7 +396,7 @@ if (!RemainingExpr.startswith(")")) return std::make_pair( - unexpectedToken(RemainingExpr, Expr, "expected ')'"), ""); + unexpectedToken(RemainingExpr, Expr, "expected ')'"), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); uint64_t StubAddr; @@ -401,7 +405,7 @@ FileName, SectionName, PCtx.IsInsideLoad); if (ErrorMsg != "") - return std::make_pair(EvalResult(ErrorMsg), ""); + return std::make_pair(EvalResult(ErrorMsg), Empty); return std::make_pair(EvalResult(StubAddr), RemainingExpr); } @@ -433,7 +437,7 @@ ErrMsg += " (this appears to be an assembler local label - " " perhaps drop the 'L'?)"; - return std::make_pair(EvalResult(ErrMsg), ""); + return std::make_pair(EvalResult(ErrMsg), StringRef("")); } // The value for the symbol depends on the context we're evaluating in: @@ -473,7 +477,8 @@ if (ValueStr.empty() || !isdigit(ValueStr[0])) return std::make_pair( - unexpectedToken(RemainingExpr, RemainingExpr, "expected number"), ""); + unexpectedToken(RemainingExpr, RemainingExpr, "expected number"), + StringRef("")); uint64_t Value; ValueStr.getAsInteger(0, Value); return std::make_pair(EvalResult(Value), RemainingExpr); @@ -490,10 +495,10 @@ std::tie(SubExprResult, RemainingExpr) = evalComplexExpr(evalSimpleExpr(Expr.substr(1).ltrim(), PCtx), PCtx); if (SubExprResult.hasError()) - return std::make_pair(SubExprResult, ""); + return std::make_pair(SubExprResult, StringRef("")); if (!RemainingExpr.startswith(")")) return std::make_pair( - unexpectedToken(RemainingExpr, Expr, "expected ')'"), ""); + unexpectedToken(RemainingExpr, Expr, "expected ')'"), StringRef("")); RemainingExpr = RemainingExpr.substr(1).ltrim(); return std::make_pair(SubExprResult, RemainingExpr); } @@ -505,10 +510,11 @@ std::pair evalLoadExpr(StringRef Expr) const { assert(Expr.startswith("*") && "Not a load expression"); StringRef RemainingExpr = Expr.substr(1).ltrim(); + StringRef Empty(""); // Parse read size. if (!RemainingExpr.startswith("{")) - return std::make_pair(EvalResult("Expected '{' following '*'."), ""); + return std::make_pair(EvalResult("Expected '{' following '*'."), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); EvalResult ReadSizeExpr; std::tie(ReadSizeExpr, RemainingExpr) = evalNumberExpr(RemainingExpr); @@ -516,9 +522,9 @@ return std::make_pair(ReadSizeExpr, RemainingExpr); uint64_t ReadSize = ReadSizeExpr.getValue(); if (ReadSize < 1 || ReadSize > 8) - return std::make_pair(EvalResult("Invalid size for dereference."), ""); + return std::make_pair(EvalResult("Invalid size for dereference."), Empty); if (!RemainingExpr.startswith("}")) - return std::make_pair(EvalResult("Missing '}' for dereference."), ""); + return std::make_pair(EvalResult("Missing '}' for dereference."), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); // Evaluate the expression representing the load address. @@ -528,7 +534,7 @@ evalComplexExpr(evalSimpleExpr(RemainingExpr, LoadCtx), LoadCtx); if (LoadAddrExprResult.hasError()) - return std::make_pair(LoadAddrExprResult, ""); + return std::make_pair(LoadAddrExprResult, Empty); uint64_t LoadAddr = LoadAddrExprResult.getValue(); @@ -548,9 +554,10 @@ ParseContext PCtx) const { EvalResult SubExprResult; StringRef RemainingExpr; + StringRef Empty(""); if (Expr.empty()) - return std::make_pair(EvalResult("Unexpected end of expression"), ""); + return std::make_pair(EvalResult("Unexpected end of expression"), Empty); if (Expr[0] == '(') std::tie(SubExprResult, RemainingExpr) = evalParensExpr(Expr, PCtx); @@ -563,7 +570,8 @@ else return std::make_pair( unexpectedToken(Expr, Expr, - "expected '(', '*', identifier, or number"), ""); + "expected '(', '*', identifier, or number"), + Empty); if (SubExprResult.hasError()) return std::make_pair(SubExprResult, RemainingExpr); @@ -588,6 +596,7 @@ EvalResult SubExprResult; StringRef RemainingExpr; std::tie(SubExprResult, RemainingExpr) = Ctx; + StringRef Empty(""); assert(RemainingExpr.startswith("[") && "Not a slice expr."); RemainingExpr = RemainingExpr.substr(1).ltrim(); @@ -600,7 +609,7 @@ if (!RemainingExpr.startswith(":")) return std::make_pair( - unexpectedToken(RemainingExpr, RemainingExpr, "expected ':'"), ""); + unexpectedToken(RemainingExpr, RemainingExpr, "expected ':'"), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); EvalResult LowBitExpr; @@ -611,7 +620,7 @@ if (!RemainingExpr.startswith("]")) return std::make_pair( - unexpectedToken(RemainingExpr, RemainingExpr, "expected ']'"), ""); + unexpectedToken(RemainingExpr, RemainingExpr, "expected ']'"), Empty); RemainingExpr = RemainingExpr.substr(1).ltrim(); unsigned HighBit = HighBitExpr.getValue(); @@ -636,7 +645,7 @@ // If there was an error, or there's nothing left to evaluate, return the // result. - if (LHSResult.hasError() || RemainingExpr == "") + if (LHSResult.hasError() || RemainingExpr.empty()) return std::make_pair(LHSResult, RemainingExpr); // Otherwise check if this is a binary expressioan. @@ -882,7 +891,7 @@ for (auto &StubMapEntry : RTDyldStubs) { std::string SymbolName = ""; - if (StubMapEntry.first.SymbolName) + if (!StubMapEntry.first.SymbolName.empty()) SymbolName = StubMapEntry.first.SymbolName; else { // If this is a (Section, Offset) pair, do a reverse lookup in the Index: llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp =================================================================== --- llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp +++ llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp @@ -789,7 +789,7 @@ // relocation) without a .toc directive. In this case just use the // first section (which is usually the .odp) since the code won't // reference the .toc base directly. - Rel.SymbolName = nullptr; + Rel.SymbolName = StringRef(); Rel.SectionID = 0; // The TOC consists of sections .got, .toc, .tocbss, .plt in that @@ -1158,7 +1158,7 @@ void RuntimeDyldELF::processSimpleRelocation(unsigned SectionID, uint64_t Offset, unsigned RelType, RelocationValueRef Value) { RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset); - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); @@ -1214,7 +1214,7 @@ // Search for the symbol in the global symbol table RTDyldSymbolTable::const_iterator gsi = GlobalSymbolTable.end(); if (Symbol != Obj.symbol_end()) { - gsi = GlobalSymbolTable.find(TargetName.data()); + gsi = GlobalSymbolTable.find(TargetName); Expected SymTypeOrErr = Symbol->getType(); if (!SymTypeOrErr) { std::string Buf; @@ -1260,14 +1260,14 @@ case SymbolRef::ST_Data: case SymbolRef::ST_Function: case SymbolRef::ST_Unknown: { - Value.SymbolName = TargetName.data(); + Value.SymbolName = TargetName; Value.Addend = Addend; // Absolute relocations will have a zero symbol ID (STN_UNDEF), which // will manifest here as a NULL symbol name. // We can set this as a valid (but empty) symbol name, and rely // on addRelocationForSymbol to handle this. - if (!Value.SymbolName) + if (Value.SymbolName.empty()) Value.SymbolName = ""; break; } @@ -1314,7 +1314,7 @@ Section.getAddress() + 12, ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend); - if (Value.SymbolName) { + if (!Value.SymbolName.empty()) { addRelocationForSymbol(REmovz_g3, Value.SymbolName); addRelocationForSymbol(REmovk_g2, Value.SymbolName); addRelocationForSymbol(REmovk_g1, Value.SymbolName); @@ -1354,7 +1354,7 @@ Section.getAddressWithOffset(Section.getStubOffset())); RelocationEntry RE(SectionID, StubTargetAddr - Section.getAddress(), ELF::R_ARM_ABS32, Value.Addend); - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); @@ -1417,7 +1417,7 @@ StubTargetAddr - Section.getAddress() + 4, ELF::R_MIPS_LO16, Value.Addend); - if (Value.SymbolName) { + if (!Value.SymbolName.empty()) { addRelocationForSymbol(REHi, Value.SymbolName); addRelocationForSymbol(RELo, Value.SymbolName); } @@ -1443,7 +1443,7 @@ RelType == getMatchingLoRelocation(Reloc.RelType) && SectionID == Reloc.SectionID) { Reloc.Addend += Addend; - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(Reloc, Value.SymbolName); else addRelocationForSection(Reloc, Value.SectionID); @@ -1452,7 +1452,7 @@ ++I; } RelocationEntry RE(SectionID, Offset, RelType, Addend); - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); @@ -1482,7 +1482,7 @@ GOTSymbolOffsets[TargetName] = RE.SymOffset; } } - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); @@ -1517,7 +1517,7 @@ // If it is within 26-bits branch range, just set the branch target if (SignExtend32<26>(delta) == delta) { RelocationEntry RE(SectionID, Offset, RelType, Value.Addend); - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); @@ -1563,7 +1563,7 @@ RelocationEntry REl(SectionID, StubRelocOffset + 16, ELF::R_PPC64_ADDR16_LO, Value.Addend); - if (Value.SymbolName) { + if (!Value.SymbolName.empty()) { addRelocationForSymbol(REhst, Value.SymbolName); addRelocationForSymbol(REhr, Value.SymbolName); addRelocationForSymbol(REh, Value.SymbolName); @@ -1618,7 +1618,7 @@ RelocationValueRef TOCValue; if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, TOCValue)) return std::move(Err); - if (Value.SymbolName || Value.SectionID != TOCValue.SectionID) + if (!Value.SymbolName.empty() || Value.SectionID != TOCValue.SectionID) llvm_unreachable("Unsupported TOC relocation."); Value.Addend -= TOCValue.Addend; resolveRelocation(Sections[SectionID], Offset, Value.Addend, RelType, 0); @@ -1639,7 +1639,7 @@ RelocationEntry RE(SectionID, Offset, RelType, Value.Addend); - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); @@ -1679,7 +1679,7 @@ createStubFunction((uint8_t *)StubAddress); RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64, Value.Offset); - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); @@ -1709,7 +1709,7 @@ // equivalent to the usual PLT implementation except that we use the stub // mechanism in RuntimeDyld (which puts stubs at the end of the section) // rather than allocating a PLT section. - if (Value.SymbolName) { + if (!Value.SymbolName.empty()) { // This is a call to an external function. // Look for an existing stub. SectionEntry &Section = Sections[SectionID]; @@ -1762,7 +1762,7 @@ // Fill in the value of the symbol we're targeting into the GOT RelocationEntry RE = computeGOTOffsetRE(SectionID, GOTOffset, Value.Offset, ELF::R_X86_64_64); - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); Index: llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h =================================================================== --- llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h +++ llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h @@ -179,9 +179,8 @@ unsigned SectionID; uint64_t Offset; int64_t Addend; - const char *SymbolName; - RelocationValueRef() : SectionID(0), Offset(0), Addend(0), - SymbolName(nullptr) {} + StringRef SymbolName; + RelocationValueRef() : SectionID(0), Offset(0), Addend(0) {} inline bool operator==(const RelocationValueRef &Other) const { return SectionID == Other.SectionID && Offset == Other.Offset && Index: llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.cpp =================================================================== --- llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.cpp +++ llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.cpp @@ -110,14 +110,13 @@ TargetName = *TargetNameOrErr; else return TargetNameOrErr.takeError(); - RTDyldSymbolTable::const_iterator SI = - GlobalSymbolTable.find(TargetName.data()); + RTDyldSymbolTable::const_iterator SI = GlobalSymbolTable.find(TargetName); if (SI != GlobalSymbolTable.end()) { const auto &SymInfo = SI->second; Value.SectionID = SymInfo.getSectionID(); Value.Offset = SymInfo.getOffset() + RE.Addend; } else { - Value.SymbolName = TargetName.data(); + Value.SymbolName = TargetName; Value.Offset = RE.Addend; } } else { Index: llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOAArch64.h =================================================================== --- llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOAArch64.h +++ llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOAArch64.h @@ -301,7 +301,7 @@ RE.RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12) processGOTRelocation(RE, Value, Stubs); else { - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); @@ -407,7 +407,7 @@ RelocationEntry GOTRE(RE.SectionID, StubOffset, MachO::ARM64_RELOC_UNSIGNED, Value.Offset, /*IsPCRel=*/false, /*Size=*/3); - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(GOTRE, Value.SymbolName); else addRelocationForSection(GOTRE, Value.SectionID); Index: llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOARM.h =================================================================== --- llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOARM.h +++ llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOARM.h @@ -103,7 +103,7 @@ processBranchRelocation(RE, Value, Stubs); else { RE.Addend = Value.Offset; - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); @@ -202,7 +202,7 @@ RelocationEntry StubRE( RE.SectionID, StubTargetAddr - Section.getAddress(), MachO::GENERIC_RELOC_VANILLA, Value.Offset, false, 2); - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(StubRE, Value.SymbolName); else addRelocationForSection(StubRE, Value.SectionID); Index: llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOI386.h =================================================================== --- llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOI386.h +++ llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOI386.h @@ -88,7 +88,7 @@ RE.Addend = Value.Offset; - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); Index: llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOX86_64.h =================================================================== --- llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOX86_64.h +++ llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldMachOX86_64.h @@ -75,7 +75,7 @@ processGOTRelocation(RE, Value, Stubs); else { RE.Addend = Value.Offset; - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(RE, Value.SymbolName); else addRelocationForSection(RE, Value.SectionID); @@ -143,7 +143,7 @@ RelocationEntry GOTRE(RE.SectionID, Section.getStubOffset(), MachO::X86_64_RELOC_UNSIGNED, Value.Offset, false, 3); - if (Value.SymbolName) + if (!Value.SymbolName.empty()) addRelocationForSymbol(GOTRE, Value.SymbolName); else addRelocationForSection(GOTRE, Value.SectionID); Index: llvm/lib/IR/Core.cpp =================================================================== --- llvm/lib/IR/Core.cpp +++ llvm/lib/IR/Core.cpp @@ -213,12 +213,12 @@ /*===-- Operations on modules ---------------------------------------------===*/ LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID) { - return wrap(new Module(ModuleID, *GlobalContext)); + return wrap(new Module(StringRef(ModuleID), *GlobalContext)); } LLVMModuleRef LLVMModuleCreateWithNameInContext(const char *ModuleID, LLVMContextRef C) { - return wrap(new Module(ModuleID, *unwrap(C))); + return wrap(new Module(StringRef(ModuleID), *unwrap(C))); } void LLVMDisposeModule(LLVMModuleRef M) { @@ -246,7 +246,7 @@ } void LLVMSetDataLayout(LLVMModuleRef M, const char *DataLayoutStr) { - unwrap(M)->setDataLayout(DataLayoutStr); + unwrap(M)->setDataLayout(StringRef(DataLayoutStr)); } /*--.. Target triple .......................................................--*/ @@ -255,7 +255,7 @@ } void LLVMSetTarget(LLVMModuleRef M, const char *Triple) { - unwrap(M)->setTargetTriple(Triple); + unwrap(M)->setTargetTriple(StringRef(Triple)); } void LLVMDumpModule(LLVMModuleRef M) { @@ -265,7 +265,7 @@ LLVMBool LLVMPrintModuleToFile(LLVMModuleRef M, const char *Filename, char **ErrorMessage) { std::error_code EC; - raw_fd_ostream dest(Filename, EC, sys::fs::F_Text); + raw_fd_ostream dest(StringRef(Filename), EC, sys::fs::F_Text); if (EC) { *ErrorMessage = strdup(EC.message().c_str()); return true; @@ -519,7 +519,7 @@ LLVMTypeRef LLVMStructCreateNamed(LLVMContextRef C, const char *Name) { - return wrap(StructType::create(*unwrap(C), Name)); + return wrap(StructType::create(*unwrap(C), StringRef(Name))); } const char *LLVMGetStructName(LLVMTypeRef Ty) @@ -561,7 +561,7 @@ } LLVMTypeRef LLVMGetTypeByName(LLVMModuleRef M, const char *Name) { - return wrap(unwrap(M)->getTypeByName(Name)); + return wrap(unwrap(M)->getTypeByName(StringRef(Name))); } /*--.. Operations on array, pointer, and vector types (sequence types) .....--*/ @@ -907,7 +907,7 @@ void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char *Name, LLVMValueRef Val) { - NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(Name); + NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(StringRef(Name)); if (!N) return; if (!Val) @@ -1425,8 +1425,9 @@ const char *Constraints, LLVMBool HasSideEffects, LLVMBool IsAlignStack) { - return wrap(InlineAsm::get(dyn_cast(unwrap(Ty)), AsmString, - Constraints, HasSideEffects, IsAlignStack)); + return wrap(InlineAsm::get(dyn_cast(unwrap(Ty)), + StringRef(AsmString), StringRef(Constraints), + HasSideEffects, IsAlignStack)); } LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB) { @@ -1541,7 +1542,7 @@ } void LLVMSetSection(LLVMValueRef Global, const char *Section) { - unwrap(Global)->setSection(Section); + unwrap(Global)->setSection(StringRef(Section)); } LLVMVisibility LLVMGetVisibility(LLVMValueRef Global) { @@ -1623,7 +1624,7 @@ } LLVMValueRef LLVMGetNamedGlobal(LLVMModuleRef M, const char *Name) { - return wrap(unwrap(M)->getNamedGlobal(Name)); + return wrap(unwrap(M)->getNamedGlobal(StringRef(Name))); } LLVMValueRef LLVMGetFirstGlobal(LLVMModuleRef M) { @@ -1756,7 +1757,7 @@ } LLVMValueRef LLVMGetNamedFunction(LLVMModuleRef M, const char *Name) { - return wrap(unwrap(M)->getFunction(Name)); + return wrap(unwrap(M)->getFunction(StringRef(Name))); } LLVMValueRef LLVMGetFirstFunction(LLVMModuleRef M) { @@ -1893,7 +1894,7 @@ AttributeSet::AttrIndex(AttributeSet::FunctionIndex); AttrBuilder B; - B.addAttribute(A, V); + B.addAttribute(StringRef(A), StringRef(V)); AttributeSet Set = AttributeSet::get(Func->getContext(), Idx, B); Func->addAttributes(Idx, Set); } @@ -2835,12 +2836,13 @@ LLVMValueRef LLVMBuildGlobalString(LLVMBuilderRef B, const char *Str, const char *Name) { - return wrap(unwrap(B)->CreateGlobalString(Str, Name)); + return wrap(unwrap(B)->CreateGlobalString(StringRef(Str), StringRef(Name))); } LLVMValueRef LLVMBuildGlobalStringPtr(LLVMBuilderRef B, const char *Str, const char *Name) { - return wrap(unwrap(B)->CreateGlobalStringPtr(Str, Name)); + return wrap( + unwrap(B)->CreateGlobalStringPtr(StringRef(Str), StringRef(Name))); } LLVMBool LLVMGetVolatile(LLVMValueRef MemAccessInst) { Index: llvm/lib/IR/Function.cpp =================================================================== --- llvm/lib/IR/Function.cpp +++ llvm/lib/IR/Function.cpp @@ -452,8 +452,8 @@ } /// Table of string intrinsic names indexed by enum value. -static const char * const IntrinsicNameTable[] = { - "not_intrinsic", +static constexpr StringRef IntrinsicNameTable[] = { + "not_intrinsic", #define GET_INTRINSIC_NAME_TABLE #include "llvm/IR/Intrinsics.gen" #undef GET_INTRINSIC_NAME_TABLE @@ -468,7 +468,7 @@ /// target as \c Name, or the generic table if \c Name is not target specific. /// /// Returns the relevant slice of \c IntrinsicNameTable -static ArrayRef findTargetSubtable(StringRef Name) { +static ArrayRef findTargetSubtable(StringRef Name) { assert(Name.startswith("llvm.")); ArrayRef Targets(TargetInfos); @@ -487,7 +487,7 @@ /// \brief This does the actual lookup of an intrinsic ID which /// matches the given function name. Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) { - ArrayRef NameTable = findTargetSubtable(Name); + auto NameTable = findTargetSubtable(Name); int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name); if (Idx == -1) return Intrinsic::not_intrinsic; @@ -499,7 +499,7 @@ // If the intrinsic is not overloaded, require an exact match. If it is // overloaded, require a prefix match. - bool IsPrefixMatch = Name.size() > strlen(NameTable[Idx]); + bool IsPrefixMatch = Name.size() > NameTable[Idx].size(); return IsPrefixMatch == isOverloaded(ID) ? ID : Intrinsic::not_intrinsic; } Index: llvm/lib/IR/IntrinsicInst.cpp =================================================================== --- llvm/lib/IR/IntrinsicInst.cpp +++ llvm/lib/IR/IntrinsicInst.cpp @@ -47,7 +47,7 @@ return nullptr; } -int llvm::Intrinsic::lookupLLVMIntrinsicByName(ArrayRef NameTable, +int llvm::Intrinsic::lookupLLVMIntrinsicByName(ArrayRef NameTable, StringRef Name) { assert(Name.startswith("llvm.")); @@ -60,25 +60,26 @@ // be part of the equal range. size_t CmpStart = 0; size_t CmpEnd = 4; // Skip the "llvm" component. - const char *const *Low = NameTable.begin(); - const char *const *High = NameTable.end(); - const char *const *LastLow = Low; + const StringRef *Low = NameTable.begin(); + const StringRef *High = NameTable.end(); + const StringRef *LastLow = Low; while (CmpEnd < Name.size() && High - Low > 0) { CmpStart = CmpEnd; CmpEnd = Name.find('.', CmpStart + 1); CmpEnd = CmpEnd == StringRef::npos ? Name.size() : CmpEnd; - auto Cmp = [CmpStart, CmpEnd](const char *LHS, const char *RHS) { - return strncmp(LHS + CmpStart, RHS + CmpStart, CmpEnd - CmpStart) < 0; + auto Cmp = [CmpStart, CmpEnd](StringRef LHS, StringRef RHS) { + return strncmp(LHS.data() + CmpStart, RHS.data() + CmpStart, + CmpEnd - CmpStart) < 0; }; LastLow = Low; - std::tie(Low, High) = std::equal_range(Low, High, Name.data(), Cmp); + std::tie(Low, High) = std::equal_range(Low, High, Name, Cmp); } if (High - Low > 0) LastLow = Low; if (LastLow == NameTable.end()) return -1; - StringRef NameFound = *LastLow; + StringRef NameFound(*LastLow); if (Name == NameFound || (Name.startswith(NameFound) && Name[NameFound.size()] == '.')) return LastLow - NameTable.begin(); Index: llvm/lib/IR/Module.cpp =================================================================== --- llvm/lib/IR/Module.cpp +++ llvm/lib/IR/Module.cpp @@ -521,7 +521,8 @@ GlobalVariable *llvm::collectUsedGlobalVariables( const Module &M, SmallPtrSetImpl &Set, bool CompilerUsed) { - const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used"; + auto Name = + CompilerUsed ? StringRef("llvm.compiler.used") : StringRef("llvm.used"); GlobalVariable *GV = M.getGlobalVariable(Name); if (!GV || !GV->hasInitializer()) return GV; Index: llvm/lib/IR/OptBisect.cpp =================================================================== --- llvm/lib/IR/OptBisect.cpp +++ llvm/lib/IR/OptBisect.cpp @@ -34,7 +34,7 @@ static void printPassMessage(const StringRef &Name, int PassNum, StringRef TargetDesc, bool Running) { - StringRef Status = Running ? "" : "NOT "; + StringRef Status(Running ? "" : "NOT "); errs() << "BISECT: " << Status << "running pass " << "(" << PassNum << ") " << Name << " on " << TargetDesc << "\n"; } Index: llvm/lib/IR/ProfileSummary.cpp =================================================================== --- llvm/lib/IR/ProfileSummary.cpp +++ llvm/lib/IR/ProfileSummary.cpp @@ -85,7 +85,7 @@ } // Parse an MDTuple representing (Key, Val) pair. -static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val) { +static bool getVal(MDTuple *MD, StringRef Key, uint64_t &Val) { if (!MD) return false; if (MD->getNumOperands() != 2) @@ -101,7 +101,7 @@ } // Check if an MDTuple represents a (Key, Val) pair. -static bool isKeyValuePair(MDTuple *MD, const char *Key, const char *Val) { +static bool isKeyValuePair(MDTuple *MD, StringRef Key, StringRef Val) { if (!MD || MD->getNumOperands() != 2) return false; MDString *KeyMD = dyn_cast(MD->getOperand(0)); Index: llvm/lib/IRReader/IRReader.cpp =================================================================== --- llvm/lib/IRReader/IRReader.cpp +++ llvm/lib/IRReader/IRReader.cpp @@ -26,8 +26,8 @@ extern bool TimePassesIsEnabled; } -static const char *const TimeIRParsingGroupName = "LLVM IR Parsing"; -static const char *const TimeIRParsingName = "Parse IR"; +static constexpr const char TimeIRParsingGroupName[] = "LLVM IR Parsing"; +static constexpr const char TimeIRParsingName[] = "Parse IR"; static std::unique_ptr getLazyIRModule(std::unique_ptr Buffer, SMDiagnostic &Err, @@ -113,7 +113,7 @@ std::string buf; raw_string_ostream os(buf); - Diag.print(nullptr, os, false); + Diag.print("", os, false); os.flush(); *OutMessage = strdup(buf.c_str()); Index: llvm/lib/LTO/UpdateCompilerUsed.cpp =================================================================== --- llvm/lib/LTO/UpdateCompilerUsed.cpp +++ llvm/lib/LTO/UpdateCompilerUsed.cpp @@ -79,10 +79,11 @@ // TargetLowering has info on library calls that CodeGen expects to be // available, both from the C runtime and compiler-rt. for (unsigned I = 0, E = static_cast(RTLIB::UNKNOWN_LIBCALL); - I != E; ++I) - if (const char *Name = - Lowering->getLibcallName(static_cast(I))) + I != E; ++I) { + auto Name = Lowering->getLibcallName(static_cast(I)); + if (!Name.empty()) Libcalls.insert(Name); + } } } Index: llvm/lib/LibDriver/LibDriver.cpp =================================================================== --- llvm/lib/LibDriver/LibDriver.cpp +++ llvm/lib/LibDriver/LibDriver.cpp @@ -157,7 +157,7 @@ if (Result.second) { if (Result.first.empty()) - Result.first = ArgsArr[0]; + Result.first = StringRef(ArgsArr[0]); llvm::errs() << Result.first << ": " << Result.second.message() << "\n"; return 1; } Index: llvm/lib/MC/ELFObjectWriter.cpp =================================================================== --- llvm/lib/MC/ELFObjectWriter.cpp +++ llvm/lib/MC/ELFObjectWriter.cpp @@ -866,7 +866,7 @@ Buf += Name.substr(0, Pos); unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1; Buf += Name.substr(Pos + Skip); - Name = VersionSymSaver.save(Buf.c_str()); + Name = StringRef(VersionSymSaver.save(StringRef(Buf.c_str()))); } } Index: llvm/lib/MC/MCDisassembler/Disassembler.cpp =================================================================== --- llvm/lib/MC/MCDisassembler/Disassembler.cpp +++ llvm/lib/MC/MCDisassembler/Disassembler.cpp @@ -43,12 +43,13 @@ // disassembler context. If not, it returns NULL. // LLVMDisasmContextRef -LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU, +LLVMCreateDisasmCPUFeatures(const char *TT_CStr, const char *CPU, const char *Features, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp) { // Get the target. std::string Error; + StringRef TT(TT_CStr); const Target *TheTarget = TargetRegistry::lookupTarget(TT, Error); if (!TheTarget) return nullptr; @@ -67,7 +68,7 @@ return nullptr; const MCSubtargetInfo *STI = - TheTarget->createMCSubtargetInfo(TT, CPU, Features); + TheTarget->createMCSubtargetInfo(TT, StringRef(CPU), StringRef(Features)); if (!STI) return nullptr; Index: llvm/lib/MC/MCDisassembler/MCExternalSymbolizer.cpp =================================================================== --- llvm/lib/MC/MCDisassembler/MCExternalSymbolizer.cpp +++ llvm/lib/MC/MCDisassembler/MCExternalSymbolizer.cpp @@ -166,7 +166,7 @@ else if(ReferenceType == LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr) { cStream << "literal pool for: \""; - cStream.write_escaped(ReferenceName); + cStream.write_escaped(StringRef(ReferenceName)); cStream << "\""; } else if(ReferenceType == Index: llvm/lib/MC/MachObjectWriter.cpp =================================================================== --- llvm/lib/MC/MachObjectWriter.cpp +++ llvm/lib/MC/MachObjectWriter.cpp @@ -422,7 +422,7 @@ uint64_t BytesWritten = sizeof(MachO::linker_option_command); for (const std::string &Option : Options) { // Write each string, including the null byte. - writeBytes(Option.c_str(), Option.size() + 1); + writeBytes(Option, Option.size() + 1); BytesWritten += Option.size() + 1; } Index: llvm/lib/Object/Archive.cpp =================================================================== --- llvm/lib/Object/Archive.cpp +++ llvm/lib/Object/Archive.cpp @@ -22,8 +22,8 @@ using namespace object; using namespace llvm::support::endian; -static const char *const Magic = "!\n"; -static const char *const ThinMagic = "!\n"; +static constexpr char const Magic[] = "!\n"; +static constexpr char const ThinMagic[] = "!\n"; void Archive::anchor() { } @@ -158,13 +158,13 @@ "the end of the string table for archive member " "header at offset " + Twine(ArchiveOffset)); } - const char *addr = Parent->getStringTable().begin() + StringOffset; + StringRef addr(Parent->getStringTable().begin() + StringOffset); // GNU long file names end with a "/\n". if (Parent->kind() == Archive::K_GNU || Parent->kind() == Archive::K_MIPS64) { StringRef::size_type End = StringRef(addr).find('\n'); - return StringRef(addr, End - 1); + return addr.take_front(End - 1); } return addr; } @@ -775,7 +775,7 @@ } StringRef Archive::Symbol::getName() const { - return Parent->getSymbolTable().begin() + StringIndex; + return StringRef(Parent->getSymbolTable().begin() + StringIndex); } Expected Archive::Symbol::getMember() const { Index: llvm/lib/Object/ArchiveWriter.cpp =================================================================== --- llvm/lib/Object/ArchiveWriter.cpp +++ llvm/lib/Object/ArchiveWriter.cpp @@ -416,5 +416,5 @@ OldArchiveBuf.reset(); sys::fs::rename(TmpArchive, ArcName); - return std::make_pair("", std::error_code()); + return std::make_pair(StringRef(""), std::error_code()); } Index: llvm/lib/Object/MachOObjectFile.cpp =================================================================== --- llvm/lib/Object/MachOObjectFile.cpp +++ llvm/lib/Object/MachOObjectFile.cpp @@ -100,7 +100,7 @@ static StringRef parseSegmentOrSectionName(const char *P) { if (P[15] == 0) // Null terminated. - return P; + return StringRef(P); // Not null terminated, so this is a 16 char string. return StringRef(P, 16); } @@ -1407,13 +1407,10 @@ switch (Arch) { case Triple::x86: { - static const char *const Table[] = { - "GENERIC_RELOC_VANILLA", - "GENERIC_RELOC_PAIR", - "GENERIC_RELOC_SECTDIFF", - "GENERIC_RELOC_PB_LA_PTR", - "GENERIC_RELOC_LOCAL_SECTDIFF", - "GENERIC_RELOC_TLV" }; + static constexpr StringRef Table[] = { + "GENERIC_RELOC_VANILLA", "GENERIC_RELOC_PAIR", + "GENERIC_RELOC_SECTDIFF", "GENERIC_RELOC_PB_LA_PTR", + "GENERIC_RELOC_LOCAL_SECTDIFF", "GENERIC_RELOC_TLV"}; if (RType > 5) res = "Unknown"; @@ -1422,17 +1419,12 @@ break; } case Triple::x86_64: { - static const char *const Table[] = { - "X86_64_RELOC_UNSIGNED", - "X86_64_RELOC_SIGNED", - "X86_64_RELOC_BRANCH", - "X86_64_RELOC_GOT_LOAD", - "X86_64_RELOC_GOT", - "X86_64_RELOC_SUBTRACTOR", - "X86_64_RELOC_SIGNED_1", - "X86_64_RELOC_SIGNED_2", - "X86_64_RELOC_SIGNED_4", - "X86_64_RELOC_TLV" }; + static constexpr StringRef Table[] = { + "X86_64_RELOC_UNSIGNED", "X86_64_RELOC_SIGNED", + "X86_64_RELOC_BRANCH", "X86_64_RELOC_GOT_LOAD", + "X86_64_RELOC_GOT", "X86_64_RELOC_SUBTRACTOR", + "X86_64_RELOC_SIGNED_1", "X86_64_RELOC_SIGNED_2", + "X86_64_RELOC_SIGNED_4", "X86_64_RELOC_TLV"}; if (RType > 9) res = "Unknown"; @@ -1441,17 +1433,12 @@ break; } case Triple::arm: { - static const char *const Table[] = { - "ARM_RELOC_VANILLA", - "ARM_RELOC_PAIR", - "ARM_RELOC_SECTDIFF", - "ARM_RELOC_LOCAL_SECTDIFF", - "ARM_RELOC_PB_LA_PTR", - "ARM_RELOC_BR24", - "ARM_THUMB_RELOC_BR22", - "ARM_THUMB_32BIT_BRANCH", - "ARM_RELOC_HALF", - "ARM_RELOC_HALF_SECTDIFF" }; + static constexpr StringRef Table[] = { + "ARM_RELOC_VANILLA", "ARM_RELOC_PAIR", + "ARM_RELOC_SECTDIFF", "ARM_RELOC_LOCAL_SECTDIFF", + "ARM_RELOC_PB_LA_PTR", "ARM_RELOC_BR24", + "ARM_THUMB_RELOC_BR22", "ARM_THUMB_32BIT_BRANCH", + "ARM_RELOC_HALF", "ARM_RELOC_HALF_SECTDIFF"}; if (RType > 9) res = "Unknown"; @@ -1460,14 +1447,17 @@ break; } case Triple::aarch64: { - static const char *const Table[] = { - "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR", - "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21", - "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21", - "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT", - "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12", - "ARM64_RELOC_ADDEND" - }; + static constexpr StringRef Table[] = {"ARM64_RELOC_UNSIGNED", + "ARM64_RELOC_SUBTRACTOR", + "ARM64_RELOC_BRANCH26", + "ARM64_RELOC_PAGE21", + "ARM64_RELOC_PAGEOFF12", + "ARM64_RELOC_GOT_LOAD_PAGE21", + "ARM64_RELOC_GOT_LOAD_PAGEOFF12", + "ARM64_RELOC_POINTER_TO_GOT", + "ARM64_RELOC_TLVP_LOAD_PAGE21", + "ARM64_RELOC_TLVP_LOAD_PAGEOFF12", + "ARM64_RELOC_ADDEND"}; if (RType >= array_lengthof(Table)) res = "Unknown"; @@ -1476,23 +1466,15 @@ break; } case Triple::ppc: { - static const char *const Table[] = { - "PPC_RELOC_VANILLA", - "PPC_RELOC_PAIR", - "PPC_RELOC_BR14", - "PPC_RELOC_BR24", - "PPC_RELOC_HI16", - "PPC_RELOC_LO16", - "PPC_RELOC_HA16", - "PPC_RELOC_LO14", - "PPC_RELOC_SECTDIFF", - "PPC_RELOC_PB_LA_PTR", - "PPC_RELOC_HI16_SECTDIFF", - "PPC_RELOC_LO16_SECTDIFF", - "PPC_RELOC_HA16_SECTDIFF", - "PPC_RELOC_JBSR", - "PPC_RELOC_LO14_SECTDIFF", - "PPC_RELOC_LOCAL_SECTDIFF" }; + static constexpr StringRef Table[] = { + "PPC_RELOC_VANILLA", "PPC_RELOC_PAIR", + "PPC_RELOC_BR14", "PPC_RELOC_BR24", + "PPC_RELOC_HI16", "PPC_RELOC_LO16", + "PPC_RELOC_HA16", "PPC_RELOC_LO14", + "PPC_RELOC_SECTDIFF", "PPC_RELOC_PB_LA_PTR", + "PPC_RELOC_HI16_SECTDIFF", "PPC_RELOC_LO16_SECTDIFF", + "PPC_RELOC_HA16_SECTDIFF", "PPC_RELOC_JBSR", + "PPC_RELOC_LO14_SECTDIFF", "PPC_RELOC_LOCAL_SECTDIFF"}; if (RType > 15) res = "Unknown"; Index: llvm/lib/Option/ArgList.cpp =================================================================== --- llvm/lib/Option/ArgList.cpp +++ llvm/lib/Option/ArgList.cpp @@ -340,7 +340,7 @@ StringRef Cur(getArgString(Index)); if (Cur.size() == LHS.size() + RHS.size() && Cur.startswith(LHS) && Cur.endswith(RHS)) - return Cur.data(); + return Cur; return MakeArgString(LHS + RHS); } @@ -378,7 +378,7 @@ // Tuck away so we have a reliable const char *. SynthesizedStrings.push_back(String0); - ArgStrings.push_back(SynthesizedStrings.back().c_str()); + ArgStrings.push_back(SynthesizedStrings.back()); return Index; } Index: llvm/lib/Option/OptTable.cpp =================================================================== --- llvm/lib/Option/OptTable.cpp +++ llvm/lib/Option/OptTable.cpp @@ -64,7 +64,7 @@ for (const char * const *APre = A.Prefixes, * const *BPre = B.Prefixes; *APre != nullptr && *BPre != nullptr; ++APre, ++BPre){ - if (int N = StrCmpOptionName(*APre, *BPre)) + if (int N = StrCmpOptionName(StringRef(*APre), StringRef(*BPre))) return N < 0; } @@ -77,7 +77,7 @@ #endif // Support lower_bound between info and an option name. -static inline bool operator<(const OptTable::Info &I, const char *Name) { +static inline bool operator<(const OptTable::Info &I, StringRef Name) { return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0; } } @@ -202,7 +202,7 @@ StringRef Name = StringRef(Str).ltrim(PrefixChars); // Search for the first next option which could be a prefix. - Start = std::lower_bound(Start, End, Name.data()); + Start = std::lower_bound(Start, End, Name); // Options are stored in sorted order, with '\0' at the end of the // alphabet. Since the only options which can accept a string must Index: llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp =================================================================== --- llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp +++ llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp @@ -538,7 +538,7 @@ } return Error::success(); } -static const char *TestingFormatMagic = "llvmcovmtestdata"; +static const char TestingFormatMagic[] = "llvmcovmtestdata"; static Error loadTestingFormat(StringRef Data, InstrProfSymtab &ProfileNames, StringRef &CoverageMapping, Index: llvm/lib/ProfileData/InstrProfReader.cpp =================================================================== --- llvm/lib/ProfileData/InstrProfReader.cpp +++ llvm/lib/ProfileData/InstrProfReader.cpp @@ -106,9 +106,8 @@ // Verify that this really looks like plain ASCII text by checking a // 'reasonable' number of characters (up to profile magic size). size_t count = std::min(Buffer.getBufferSize(), sizeof(uint64_t)); - StringRef buffer = Buffer.getBufferStart(); - return count == 0 || - std::all_of(buffer.begin(), buffer.begin() + count, + auto buffer = Buffer.getBufferStart(); + return std::all_of(buffer, buffer + count, [](char c) { return ::isprint(c) || ::isspace(c); }); } Index: llvm/lib/Support/CommandLine.cpp =================================================================== --- llvm/lib/Support/CommandLine.cpp +++ llvm/lib/Support/CommandLine.cpp @@ -735,7 +735,7 @@ // End the token if this is whitespace. if (isWhitespace(Src[I])) { if (!Token.empty()) - NewArgv.push_back(Saver.save(StringRef(Token)).data()); + NewArgv.push_back(Saver.save(StringRef(Token))); Token.clear(); continue; } @@ -746,7 +746,7 @@ // Append the last token after hitting EOF with no whitespace. if (!Token.empty()) - NewArgv.push_back(Saver.save(StringRef(Token)).data()); + NewArgv.push_back(Saver.save(StringRef(Token))); // Mark the end of response files if (MarkEOLs) NewArgv.push_back(StringRef()); @@ -827,7 +827,7 @@ if (State == UNQUOTED) { // Whitespace means the end of the token. if (isWhitespace(Src[I])) { - NewArgv.push_back(Saver.save(StringRef(Token)).data()); + NewArgv.push_back(Saver.save(StringRef(Token))); Token.clear(); State = INIT; // Mark the end of lines in response files @@ -862,7 +862,7 @@ } // Append the last token after hitting EOF with no whitespace. if (!Token.empty()) - NewArgv.push_back(Saver.save(StringRef(Token)).data()); + NewArgv.push_back(Saver.save(StringRef(Token))); // Mark the end of response files if (MarkEOLs) NewArgv.push_back(StringRef()); @@ -970,7 +970,7 @@ SmallVector newArgv; BumpPtrAllocator A; StringSaver Saver(A); - newArgv.push_back(Saver.save(progName).data()); + newArgv.push_back(Saver.save(progName)); // Parse the value of the environment variable into a "command line" // and hand it off to ParseCommandLineOptions(). Index: llvm/lib/Support/DynamicLibrary.cpp =================================================================== --- llvm/lib/Support/DynamicLibrary.cpp +++ llvm/lib/Support/DynamicLibrary.cpp @@ -113,7 +113,8 @@ // First check symbols added via AddSymbol(). if (ExplicitSymbols.isConstructed()) { - StringMap::iterator i = ExplicitSymbols->find(symbolName); + StringMap::iterator i = + ExplicitSymbols->find(StringRef(symbolName)); if (i != ExplicitSymbols->end()) return i->second; @@ -184,6 +185,7 @@ } void LLVMAddSymbol(const char *symbolName, void *symbolValue) { - return llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolValue); + return llvm::sys::DynamicLibrary::AddSymbol(StringRef(symbolName), + symbolValue); } Index: llvm/lib/Support/GraphWriter.cpp =================================================================== --- llvm/lib/Support/GraphWriter.cpp +++ llvm/lib/Support/GraphWriter.cpp @@ -57,10 +57,10 @@ /// from a reasonable number of colors. StringRef llvm::DOT::getColorString(unsigned ColorNumber) { static const int NumColors = 20; - static const char* Colors[NumColors] = { - "aaaaaa", "aa0000", "00aa00", "aa5500", "0055ff", "aa00aa", "00aaaa", - "555555", "ff5555", "55ff55", "ffff55", "5555ff", "ff55ff", "55ffff", - "ffaaaa", "aaffaa", "ffffaa", "aaaaff", "ffaaff", "aaffff"}; + static const char Colors[NumColors][7] = { + "aaaaaa", "aa0000", "00aa00", "aa5500", "0055ff", "aa00aa", "00aaaa", + "555555", "ff5555", "55ff55", "ffff55", "5555ff", "ff55ff", "55ffff", + "ffaaaa", "aaffaa", "ffffaa", "aaaaff", "ffaaff", "aaffff"}; return Colors[ColorNumber % NumColors]; } @@ -214,7 +214,7 @@ // PostScript or PDF graph generator + PostScript/PDF viewer std::string GeneratorPath; if (Viewer && - (S.TryFindProgram(getProgramName(program), GeneratorPath) || + (S.TryFindProgram(StringRef(getProgramName(program)), GeneratorPath) || S.TryFindProgram("dot|fdp|neato|twopi|circo", GeneratorPath))) { std::string OutputFilename = Filename + (Viewer == VK_CmdStart ? ".pdf" : ".ps"); Index: llvm/lib/Support/SourceMgr.cpp =================================================================== --- llvm/lib/Support/SourceMgr.cpp +++ llvm/lib/Support/SourceMgr.cpp @@ -333,7 +333,7 @@ return c & 0x80; } -void SMDiagnostic::print(const char *ProgName, raw_ostream &S, bool ShowColors, +void SMDiagnostic::print(StringRef ProgName, raw_ostream &S, bool ShowColors, bool ShowKindLabel) const { // Display colors only if OS supports colors. ShowColors &= S.has_colors(); @@ -341,7 +341,7 @@ if (ShowColors) S.changeColor(raw_ostream::SAVEDCOLOR, true); - if (ProgName && ProgName[0]) + if (!ProgName.empty()) S << ProgName << ": "; if (!Filename.empty()) { Index: llvm/lib/Support/Unix/Process.inc =================================================================== --- llvm/lib/Support/Unix/Process.inc +++ llvm/lib/Support/Unix/Process.inc @@ -187,7 +187,7 @@ SpecificBumpPtrAllocator &) { ArgsOut.reserve(ArgsIn.size()); for (auto Arg : ArgsIn) - ArgsOut.push_back(Arg); + ArgsOut.push_back(StringRef(Arg)); return std::error_code(); } Index: llvm/lib/Support/Unix/Program.inc =================================================================== --- llvm/lib/Support/Unix/Program.inc +++ llvm/lib/Support/Unix/Program.inc @@ -79,7 +79,7 @@ SmallVector EnvironmentPaths; if (Paths.empty()) if (const char *PathEnv = std::getenv("PATH")) { - SplitString(PathEnv, EnvironmentPaths, ":"); + SplitString(StringRef(PathEnv), EnvironmentPaths, ":"); Paths = EnvironmentPaths; } Index: llvm/lib/Support/YAMLTraits.cpp =================================================================== --- llvm/lib/Support/YAMLTraits.cpp +++ llvm/lib/Support/YAMLTraits.cpp @@ -141,7 +141,7 @@ return false; } MN->ValidKeys.push_back(Key); - HNode *Value = MN->Mapping[Key].get(); + HNode *Value = MN->Mapping[StringRef(Key)].get(); if (!Value) { if (Required) setError(CurrentNode, Twine("missing required key '") + Key + "'"); @@ -238,7 +238,7 @@ if (ScalarMatchFound) return false; if (ScalarHNode *SN = dyn_cast(CurrentNode)) { - if (SN->value().equals(Str)) { + if (SN->value().equals(StringRef(Str))) { ScalarMatchFound = true; return true; } @@ -277,7 +277,7 @@ unsigned Index = 0; for (auto &N : SQ->Entries) { if (ScalarHNode *SN = dyn_cast(N.get())) { - if (SN->value().equals(Str)) { + if (SN->value().equals(StringRef(Str))) { BitValuesUsed[Index] = true; return true; } @@ -378,7 +378,7 @@ bool Input::MapHNode::isValidKey(StringRef Key) { for (const char *K : ValidKeys) { - if (Key.equals(K)) + if (Key.equals(StringRef(K))) return true; } return false; @@ -460,10 +460,10 @@ if (Required || !SameAsDefault) { auto State = StateStack.back(); if (State == inFlowMapFirstKey || State == inFlowMapOtherKey) { - flowKey(Key); + flowKey(StringRef(Key)); } else { this->newLineCheck(); - this->paddedKey(Key); + this->paddedKey(StringRef(Key)); } return true; } @@ -564,7 +564,7 @@ bool Output::matchEnumScalar(const char *Str, bool Match) { if (Match && !EnumerationMatchFound) { this->newLineCheck(); - this->outputUpToEndOfLine(Str); + this->outputUpToEndOfLine(StringRef(Str)); EnumerationMatchFound = true; } return false; @@ -594,7 +594,7 @@ if (Matches) { if (NeedBitValueComma) output(", "); - this->output(Str); + this->output(StringRef(Str)); NeedBitValueComma = true; } return false; @@ -726,7 +726,7 @@ output(":"); const char *spaces = " "; if (key.size() < strlen(spaces)) - output(&spaces[key.size()]); + output(StringRef(&spaces[key.size()])); else output(" "); } Index: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp =================================================================== --- llvm/lib/Target/AArch64/AArch64ISelLowering.cpp +++ llvm/lib/Target/AArch64/AArch64ISelLowering.cpp @@ -2062,8 +2062,8 @@ Entry.isZExt = false; Args.push_back(Entry); - const char *LibcallName = - (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; + StringRef LibcallName((ArgVT == MVT::f64) ? "__sincos_stret" + : "__sincosf_stret"); SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); @@ -3203,7 +3203,7 @@ } } else if (ExternalSymbolSDNode *S = dyn_cast(Callee)) { - const char *Sym = S->getSymbol(); + StringRef Sym = S->getSymbol(); Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); } @@ -3211,7 +3211,7 @@ const GlobalValue *GV = G->getGlobal(); Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); } else if (ExternalSymbolSDNode *S = dyn_cast(Callee)) { - const char *Sym = S->getSymbol(); + StringRef Sym = S->getSymbol(); Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); } @@ -4426,9 +4426,9 @@ // this table could be generated automatically from RegInfo. unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT, SelectionDAG &DAG) const { - unsigned Reg = StringSwitch(RegName) - .Case("sp", AArch64::SP) - .Default(0); + unsigned Reg = StringSwitch(StringRef(RegName)) + .Case("sp", AArch64::SP) + .Default(0); if (Reg) return Reg; report_fatal_error(Twine("Invalid register name \"" Index: llvm/lib/Target/AArch64/AArch64MCInstLower.cpp =================================================================== --- llvm/lib/Target/AArch64/AArch64MCInstLower.cpp +++ llvm/lib/Target/AArch64/AArch64MCInstLower.cpp @@ -38,7 +38,7 @@ MCSymbol * AArch64MCInstLower::GetExternalSymbolSymbol(const MachineOperand &MO) const { - return Printer.GetExternalSymbolSymbol(MO.getSymbolName()); + return Printer.GetExternalSymbolSymbol(StringRef(MO.getSymbolName())); } MCOperand AArch64MCInstLower::lowerSymbolOperandDarwin(const MachineOperand &MO, Index: llvm/lib/Target/AArch64/AArch64SelectionDAGInfo.cpp =================================================================== --- llvm/lib/Target/AArch64/AArch64SelectionDAGInfo.cpp +++ llvm/lib/Target/AArch64/AArch64SelectionDAGInfo.cpp @@ -25,11 +25,13 @@ ConstantSDNode *SizeValue = dyn_cast(Size); const AArch64Subtarget &STI = DAG.getMachineFunction().getSubtarget(); - const char *bzeroEntry = - (V && V->isNullValue()) ? STI.getBZeroEntry() : nullptr; + StringRef bzeroEntry; + if (V && V->isNullValue()) + bzeroEntry = StringRef(STI.getBZeroEntry()); + // For small size (< 256), it is not beneficial to use bzero // instead of memset. - if (bzeroEntry && (!SizeValue || SizeValue->getZExtValue() > 256)) { + if (!bzeroEntry.empty() && (!SizeValue || SizeValue->getZExtValue() > 256)) { const AArch64TargetLowering &TLI = *STI.getTargetLowering(); EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout()); Index: llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp =================================================================== --- llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp +++ llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp @@ -2081,7 +2081,7 @@ auto PRFM = AArch64PRFM::lookupPRFMByEncoding(MCE->getValue()); Operands.push_back(AArch64Operand::CreatePrefetch( - prfop, PRFM ? PRFM->Name : "", S, getContext())); + prfop, StringRef(PRFM ? PRFM->Name : ""), S, getContext())); return MatchOperand_Success; } @@ -2746,7 +2746,7 @@ } auto DB = AArch64DB::lookupDBByEncoding(MCE->getValue()); Operands.push_back(AArch64Operand::CreateBarrier( - MCE->getValue(), DB ? DB->Name : "", ExprLoc, getContext())); + MCE->getValue(), StringRef(DB ? DB->Name : ""), ExprLoc, getContext())); return MatchOperand_Success; } @@ -4247,7 +4247,7 @@ } for (const auto &Extension : ExtensionMap) { - if (Extension.Name != Name) + if (StringRef(Extension.Name) != Name) continue; if (Extension.Features.none()) @@ -4298,7 +4298,7 @@ } for (const auto &Extension : ExtensionMap) { - if (Extension.Name != Name) + if (StringRef(Extension.Name) != Name) continue; if (Extension.Features.none()) Index: llvm/lib/Target/AArch64/Disassembler/AArch64ExternalSymbolizer.cpp =================================================================== --- llvm/lib/Target/AArch64/Disassembler/AArch64ExternalSymbolizer.cpp +++ llvm/lib/Target/AArch64/Disassembler/AArch64ExternalSymbolizer.cpp @@ -136,7 +136,7 @@ else if (ReferenceType == LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr) { CommentStream << "literal pool for: \""; - CommentStream.write_escaped(ReferenceName); + CommentStream.write_escaped(StringRef(ReferenceName)); CommentStream << "\""; } else if (ReferenceType == LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref) Index: llvm/lib/Target/AArch64/InstPrinter/AArch64InstPrinter.h =================================================================== --- llvm/lib/Target/AArch64/InstPrinter/AArch64InstPrinter.h +++ llvm/lib/Target/AArch64/InstPrinter/AArch64InstPrinter.h @@ -38,7 +38,7 @@ const MCSubtargetInfo &STI, raw_ostream &O); virtual StringRef getRegName(unsigned RegNo) const { - return getRegisterName(RegNo); + return StringRef(getRegisterName(RegNo)); } static const char *getRegisterName(unsigned RegNo, unsigned AltIdx = AArch64::NoRegAltName); @@ -178,7 +178,7 @@ const MCSubtargetInfo &STI, raw_ostream &O) override; StringRef getRegName(unsigned RegNo) const override { - return getRegisterName(RegNo); + return StringRef(getRegisterName(RegNo)); } static const char *getRegisterName(unsigned RegNo, unsigned AltIdx = AArch64::NoRegAltName); Index: llvm/lib/Target/AArch64/InstPrinter/AArch64InstPrinter.cpp =================================================================== --- llvm/lib/Target/AArch64/InstPrinter/AArch64InstPrinter.cpp +++ llvm/lib/Target/AArch64/InstPrinter/AArch64InstPrinter.cpp @@ -1403,10 +1403,10 @@ StringRef Name; if (Opcode == AArch64::ISB) { auto ISB = AArch64ISB::lookupISBByEncoding(Val); - Name = ISB ? ISB->Name : ""; + Name = StringRef(ISB ? ISB->Name : ""); } else { auto DB = AArch64DB::lookupDBByEncoding(Val); - Name = DB ? DB->Name : ""; + Name = StringRef(DB ? DB->Name : ""); } if (!Name.empty()) O << Name; Index: llvm/lib/Target/AMDGPU/AMDGPUIntrinsicInfo.cpp =================================================================== --- llvm/lib/Target/AMDGPU/AMDGPUIntrinsicInfo.cpp +++ llvm/lib/Target/AMDGPU/AMDGPUIntrinsicInfo.cpp @@ -23,7 +23,7 @@ AMDGPUIntrinsicInfo::AMDGPUIntrinsicInfo() : TargetIntrinsicInfo() {} -static const char *const IntrinsicNameTable[] = { +static const StringRef IntrinsicNameTable[] = { #define GET_INTRINSIC_NAME_TABLE #include "AMDGPUGenIntrinsics.inc" #undef GET_INTRINSIC_NAME_TABLE @@ -75,7 +75,7 @@ // AMDGPU enum enum starts at Intrinsic::num_intrinsics. int Idx = Intrinsic::lookupLLVMIntrinsicByName(IntrinsicNameTable, Name); if (Idx >= 0) { - bool IsPrefixMatch = Name.size() > strlen(IntrinsicNameTable[Idx]); + bool IsPrefixMatch = Name.size() > IntrinsicNameTable[Idx].size(); return IsPrefixMatch == isOverloaded(Idx + 1) ? Intrinsic::num_intrinsics + Idx : 0; Index: llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp =================================================================== --- llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp +++ llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp @@ -1819,7 +1819,7 @@ default: return MatchOperand_NoMatch; case AsmToken::Identifier: { StringRef Name = Parser.getTok().getString(); - if (!Name.equals(Prefix)) { + if (!Name.equals(StringRef(Prefix))) { return MatchOperand_NoMatch; } @@ -1860,10 +1860,11 @@ } AMDGPUAsmParser::OperandMatchResultTy -AMDGPUAsmParser::parseNamedBit(const char *Name, OperandVector &Operands, +AMDGPUAsmParser::parseNamedBit(const char *NameStr, OperandVector &Operands, enum AMDGPUOperand::ImmTy ImmTy) { int64_t Bit = 0; SMLoc S = Parser.getTok().getLoc(); + auto Name = StringRef(NameStr); // We are at the end of the statement, and this is a default argument, so // use a default value. @@ -2071,7 +2072,7 @@ HwReg.Id = ID_UNKNOWN_; const StringRef tok = Parser.getTok().getString(); for (int i = ID_SYMBOLIC_FIRST_; i < ID_SYMBOLIC_LAST_; ++i) { - if (tok == IdSymbolic[i]) { + if (tok == StringRef(IdSymbolic[i])) { HwReg.Id = i; break; } @@ -2227,7 +2228,7 @@ const int L = (Msg.Id == ID_SYSMSG) ? OP_SYS_LAST_ : OP_GS_LAST_; const StringRef Tok = Parser.getTok().getString(); for (int i = F; i < L; ++i) { - if (Tok == S[i]) { + if (Tok == StringRef(S[i])) { Operation.Id = i; break; } @@ -2630,7 +2631,7 @@ } else if (Op.Type == AMDGPUOperand::ImmTySdwaDstSel || Op.Type == AMDGPUOperand::ImmTySdwaSrc0Sel || Op.Type == AMDGPUOperand::ImmTySdwaSrc1Sel) { - res = parseSDWASel(Operands, Op.Name, Op.Type); + res = parseSDWASel(Operands, StringRef(Op.Name), Op.Type); } else if (Op.Type == AMDGPUOperand::ImmTySdwaDstUnused) { res = parseSDWADstUnused(Operands); } else { Index: llvm/lib/Target/AMDGPU/SIAnnotateControlFlow.cpp =================================================================== --- llvm/lib/Target/AMDGPU/SIAnnotateControlFlow.cpp +++ llvm/lib/Target/AMDGPU/SIAnnotateControlFlow.cpp @@ -35,13 +35,13 @@ typedef SmallVector StackVector; // Intrinsic names the control flow is annotated with -static const char *const IfIntrinsic = "llvm.amdgcn.if"; -static const char *const ElseIntrinsic = "llvm.amdgcn.else"; -static const char *const BreakIntrinsic = "llvm.amdgcn.break"; -static const char *const IfBreakIntrinsic = "llvm.amdgcn.if.break"; -static const char *const ElseBreakIntrinsic = "llvm.amdgcn.else.break"; -static const char *const LoopIntrinsic = "llvm.amdgcn.loop"; -static const char *const EndCfIntrinsic = "llvm.amdgcn.end.cf"; +static const char IfIntrinsic[] = "llvm.amdgcn.if"; +static const char ElseIntrinsic[] = "llvm.amdgcn.else"; +static const char BreakIntrinsic[] = "llvm.amdgcn.break"; +static const char IfBreakIntrinsic[] = "llvm.amdgcn.if.break"; +static const char ElseBreakIntrinsic[] = "llvm.amdgcn.else.break"; +static const char LoopIntrinsic[] = "llvm.amdgcn.loop"; +static const char EndCfIntrinsic[] = "llvm.amdgcn.end.cf"; class SIAnnotateControlFlow : public FunctionPass { DivergenceAnalysis *DA; Index: llvm/lib/Target/AMDGPU/SIISelLowering.cpp =================================================================== --- llvm/lib/Target/AMDGPU/SIISelLowering.cpp +++ llvm/lib/Target/AMDGPU/SIISelLowering.cpp @@ -1059,15 +1059,15 @@ unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, SelectionDAG &DAG) const { - unsigned Reg = StringSwitch(RegName) - .Case("m0", AMDGPU::M0) - .Case("exec", AMDGPU::EXEC) - .Case("exec_lo", AMDGPU::EXEC_LO) - .Case("exec_hi", AMDGPU::EXEC_HI) - .Case("flat_scratch", AMDGPU::FLAT_SCR) - .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) - .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) - .Default(AMDGPU::NoRegister); + unsigned Reg = StringSwitch(StringRef(RegName)) + .Case("m0", AMDGPU::M0) + .Case("exec", AMDGPU::EXEC) + .Case("exec_lo", AMDGPU::EXEC_LO) + .Case("exec_hi", AMDGPU::EXEC_HI) + .Case("flat_scratch", AMDGPU::FLAT_SCR) + .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) + .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) + .Default(AMDGPU::NoRegister); if (Reg == AMDGPU::NoRegister) { report_fatal_error(Twine("invalid register name \"" Index: llvm/lib/Target/ARM/ARMFastISel.cpp =================================================================== --- llvm/lib/Target/ARM/ARMFastISel.cpp +++ llvm/lib/Target/ARM/ARMFastISel.cpp @@ -2269,7 +2269,7 @@ if (Subtarget->genLongCalls()) MIB.addReg(CalleeReg); else - MIB.addExternalSymbol(TLI.getLibcallName(Call)); + MIB.addExternalSymbol(TLI.getLibcallName(Call).data()); // Add implicit physical register uses to the call. for (unsigned i = 0, e = RegArgs.size(); i != e; ++i) Index: llvm/lib/Target/ARM/ARMISelLowering.cpp =================================================================== --- llvm/lib/Target/ARM/ARMISelLowering.cpp +++ llvm/lib/Target/ARM/ARMISelLowering.cpp @@ -357,7 +357,7 @@ Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { static const struct { const RTLIB::Libcall Op; - const char * const Name; + const StringRef Name; const ISD::CondCode Cond; } LibraryCalls[] = { // Single-precision floating-point arithmetic. @@ -431,9 +431,9 @@ } // These libcalls are not available in 32-bit. - setLibcallName(RTLIB::SHL_I128, nullptr); - setLibcallName(RTLIB::SRL_I128, nullptr); - setLibcallName(RTLIB::SRA_I128, nullptr); + setLibcallName(RTLIB::SHL_I128, StringRef()); + setLibcallName(RTLIB::SRL_I128, StringRef()); + setLibcallName(RTLIB::SRA_I128, StringRef()); // RTLIB if (Subtarget->isAAPCS_ABI() && @@ -441,7 +441,7 @@ Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { static const struct { const RTLIB::Libcall Op; - const char * const Name; + const StringRef Name; const CallingConv::ID CC; const ISD::CondCode Cond; } LibraryCalls[] = { @@ -540,7 +540,7 @@ TM.Options.EABIVersion == EABI::EABI5) { static const struct { const RTLIB::Libcall Op; - const char *const Name; + const StringRef Name; const CallingConv::ID CC; const ISD::CondCode Cond; } MemOpsLibraryCalls[] = { @@ -563,7 +563,7 @@ if (Subtarget->isTargetWindows()) { static const struct { const RTLIB::Libcall Op; - const char * const Name; + const StringRef Name; const CallingConv::ID CC; } LibraryCalls[] = { { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, @@ -988,18 +988,20 @@ for (const auto &LC : {RTLIB::SDIVREM_I8, RTLIB::SDIVREM_I16, RTLIB::SDIVREM_I32}) - setLibcallName(LC, Subtarget->isTargetWindows() ? "__rt_sdiv" - : "__aeabi_idivmod"); - setLibcallName(RTLIB::SDIVREM_I64, Subtarget->isTargetWindows() - ? "__rt_sdiv64" - : "__aeabi_ldivmod"); + setLibcallName(LC, StringRef(Subtarget->isTargetWindows() + ? "__rt_sdiv" + : "__aeabi_idivmod")); + setLibcallName(RTLIB::SDIVREM_I64, + StringRef(Subtarget->isTargetWindows() ? "__rt_sdiv64" + : "__aeabi_ldivmod")); for (const auto &LC : {RTLIB::UDIVREM_I8, RTLIB::UDIVREM_I16, RTLIB::UDIVREM_I32}) - setLibcallName(LC, Subtarget->isTargetWindows() ? "__rt_udiv" - : "__aeabi_uidivmod"); - setLibcallName(RTLIB::UDIVREM_I64, Subtarget->isTargetWindows() - ? "__rt_udiv64" - : "__aeabi_uldivmod"); + setLibcallName(LC, StringRef(Subtarget->isTargetWindows() + ? "__rt_udiv" + : "__aeabi_uidivmod")); + setLibcallName(RTLIB::UDIVREM_I64, StringRef(Subtarget->isTargetWindows() + ? "__rt_udiv64" + : "__aeabi_uldivmod")); setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); @@ -2026,7 +2028,7 @@ PtrVt, dl, DAG.getEntryNode(), CPAddr, MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); } else if (ExternalSymbolSDNode *S=dyn_cast(Callee)) { - const char *Sym = S->getSymbol(); + StringRef Sym = S->getSymbol(); // Create a constant pool entry for the callee address unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); @@ -2089,7 +2091,7 @@ } else if (ExternalSymbolSDNode *S = dyn_cast(Callee)) { isDirect = true; // tBX takes a register source operand. - const char *Sym = S->getSymbol(); + StringRef Sym = S->getSymbol(); if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); ARMConstantPoolValue *CPV = @@ -4729,9 +4731,8 @@ // this table could be generated automatically from RegInfo. unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, SelectionDAG &DAG) const { - unsigned Reg = StringSwitch(RegName) - .Case("sp", ARM::SP) - .Default(0); + unsigned Reg = + StringSwitch(StringRef(RegName)).Case("sp", ARM::SP).Default(0); if (Reg) return Reg; report_fatal_error(Twine("Invalid register name \"" @@ -7315,8 +7316,8 @@ Entry.isZExt = false; Args.push_back(Entry); - const char *LibcallName = - (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; + StringRef LibcallName((ArgVT == MVT::f64) ? "__sincos_stret" + : "__sincosf_stret"); RTLIB::Libcall LC = (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; CallingConv::ID CC = getLibcallCallingConv(LC); @@ -7357,11 +7358,11 @@ const auto &DL = DAG.getDataLayout(); const auto &TLI = DAG.getTargetLoweringInfo(); - const char *Name = nullptr; + StringRef Name; if (Signed) - Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; + Name = StringRef((VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"); else - Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; + Name = StringRef((VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"); SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); Index: llvm/lib/Target/ARM/ARMMCInstLower.cpp =================================================================== --- llvm/lib/Target/ARM/ARMMCInstLower.cpp +++ llvm/lib/Target/ARM/ARMMCInstLower.cpp @@ -84,7 +84,7 @@ } case MachineOperand::MO_ExternalSymbol: MCOp = GetSymbolRef(MO, - GetExternalSymbolSymbol(MO.getSymbolName())); + GetExternalSymbolSymbol(StringRef(MO.getSymbolName()))); break; case MachineOperand::MO_JumpTableIndex: MCOp = GetSymbolRef(MO, GetJTISymbol(MO.getIndex())); Index: llvm/lib/Target/ARM/ARMSelectionDAGInfo.cpp =================================================================== --- llvm/lib/Target/ARM/ARMSelectionDAGInfo.cpp +++ llvm/lib/Target/ARM/ARMSelectionDAGInfo.cpp @@ -30,7 +30,7 @@ // Only use a specialized AEABI function if the default version of this // Libcall is an AEABI function. - if (std::strncmp(TLI->getLibcallName(LC), "__aeabi", 7) != 0) + if (!TLI->getLibcallName(LC).startswith("__aeabi")) return SDValue(); // Translate RTLIB::Libcall to AEABILibcall. We only do this in order to be @@ -105,12 +105,11 @@ Args.push_back(Entry); } - char const *FunctionNames[4][3] = { - { "__aeabi_memcpy", "__aeabi_memcpy4", "__aeabi_memcpy8" }, - { "__aeabi_memmove", "__aeabi_memmove4", "__aeabi_memmove8" }, - { "__aeabi_memset", "__aeabi_memset4", "__aeabi_memset8" }, - { "__aeabi_memclr", "__aeabi_memclr4", "__aeabi_memclr8" } - }; + StringRef FunctionNames[4][3] = { + {"__aeabi_memcpy", "__aeabi_memcpy4", "__aeabi_memcpy8"}, + {"__aeabi_memmove", "__aeabi_memmove4", "__aeabi_memmove8"}, + {"__aeabi_memset", "__aeabi_memset4", "__aeabi_memset8"}, + {"__aeabi_memclr", "__aeabi_memclr4", "__aeabi_memclr8"}}; TargetLowering::CallLoweringInfo CLI(DAG); CLI.setDebugLoc(dl) .setChain(Chain) Index: llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp =================================================================== --- llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp +++ llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp @@ -5483,7 +5483,7 @@ MACHO = (1 << MCObjectFileInfo::IsMachO) }; static const struct PrefixEntry { - const char *Spelling; + const StringRef Spelling; ARMMCExpr::VariantKind VariantKind; uint8_t SupportedFormats; } PrefixEntries[] = { Index: llvm/lib/Target/Hexagon/AsmParser/HexagonAsmParser.cpp =================================================================== --- llvm/lib/Target/Hexagon/AsmParser/HexagonAsmParser.cpp +++ llvm/lib/Target/Hexagon/AsmParser/HexagonAsmParser.cpp @@ -1124,8 +1124,8 @@ if (previousEqual(Operands, 0, "if")) { if (WarnMissingParenthesis) Warning (Begin, "Missing parenthesis around predicate register"); - static char const *LParen = "("; - static char const *RParen = ")"; + StringRef LParen = "("; + StringRef RParen = ")"; Operands.push_back(HexagonOperand::CreateToken(LParen, Begin)); Operands.push_back(HexagonOperand::CreateReg(Register, Begin, End)); const AsmToken &MaybeDotNew = Lexer.getTok(); @@ -1139,8 +1139,8 @@ previousEqual(Operands, 1, "if")) { if (WarnMissingParenthesis) Warning (Begin, "Missing parenthesis around predicate register"); - static char const *LParen = "("; - static char const *RParen = ")"; + StringRef LParen = "("; + StringRef RParen = ")"; Operands.insert(Operands.end () - 1, HexagonOperand::CreateToken(LParen, Begin)); Operands.push_back(HexagonOperand::CreateReg(Register, Begin, End)); @@ -1281,7 +1281,7 @@ llvm::SmallVector Tokens; MCAsmLexer &Lexer = getLexer(); bool Done = false; - static char const * Comma = ","; + StringRef Comma = ","; do { Tokens.emplace_back (Lexer.getTok()); Lex(); Index: llvm/lib/Target/Hexagon/HexagonISelLowering.cpp =================================================================== --- llvm/lib/Target/Hexagon/HexagonISelLowering.cpp +++ llvm/lib/Target/Hexagon/HexagonISelLowering.cpp @@ -2224,9 +2224,9 @@ } // These cause problems when the shift amount is non-constant. - setLibcallName(RTLIB::SHL_I128, nullptr); - setLibcallName(RTLIB::SRL_I128, nullptr); - setLibcallName(RTLIB::SRA_I128, nullptr); + setLibcallName(RTLIB::SHL_I128, StringRef()); + setLibcallName(RTLIB::SRL_I128, StringRef()); + setLibcallName(RTLIB::SRA_I128, StringRef()); } Index: llvm/lib/Target/Hexagon/HexagonMCInstLower.cpp =================================================================== --- llvm/lib/Target/Hexagon/HexagonMCInstLower.cpp +++ llvm/lib/Target/Hexagon/HexagonMCInstLower.cpp @@ -147,8 +147,9 @@ MCO = GetSymbolRef(MO, AP.getSymbol(MO.getGlobal()), AP, MustExtend); break; case MachineOperand::MO_ExternalSymbol: - MCO = GetSymbolRef(MO, AP.GetExternalSymbolSymbol(MO.getSymbolName()), - AP, MustExtend); + MCO = GetSymbolRef( + MO, AP.GetExternalSymbolSymbol(StringRef(MO.getSymbolName())), AP, + MustExtend); break; case MachineOperand::MO_JumpTableIndex: MCO = GetSymbolRef(MO, AP.GetJTISymbol(MO.getIndex()), AP, MustExtend); Index: llvm/lib/Target/Hexagon/HexagonSelectionDAGInfo.cpp =================================================================== --- llvm/lib/Target/Hexagon/HexagonSelectionDAGInfo.cpp +++ llvm/lib/Target/Hexagon/HexagonSelectionDAGInfo.cpp @@ -42,7 +42,7 @@ Entry.Node = Size; Args.push_back(Entry); - const char *SpecialMemcpyName = + StringRef SpecialMemcpyName = "__hexagon_memcpy_likely_aligned_min32bytes_mult8bytes"; const MachineFunction &MF = DAG.getMachineFunction(); bool LongCalls = MF.getSubtarget().useLongCalls(); Index: llvm/lib/Target/Hexagon/HexagonTargetObjectFile.cpp =================================================================== --- llvm/lib/Target/Hexagon/HexagonTargetObjectFile.cpp +++ llvm/lib/Target/Hexagon/HexagonTargetObjectFile.cpp @@ -69,8 +69,7 @@ Sec.find(".scommon.") != StringRef::npos; } - -static const char *getSectionSuffixForSize(unsigned Size) { +static StringRef getSectionSuffixForSize(unsigned Size) { switch (Size) { default: return ""; Index: llvm/lib/Target/Hexagon/HexagonVectorPrint.cpp =================================================================== --- llvm/lib/Target/Hexagon/HexagonVectorPrint.cpp +++ llvm/lib/Target/Hexagon/HexagonVectorPrint.cpp @@ -80,7 +80,7 @@ MachineFunction &Fn) { std::string VDescStr = ".long 0x1dffe0" + getStringReg(Reg); - const char *cstr = Fn.createExternalSymbolName(VDescStr.c_str()); + const char *cstr = Fn.createExternalSymbolName(VDescStr).data(); unsigned ExtraInfo = InlineAsm::Extra_HasSideEffects; BuildMI(*MBB, I, DL, QII->get(TargetOpcode::INLINEASM)) .addExternalSymbol(cstr) Index: llvm/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.cpp =================================================================== --- llvm/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.cpp +++ llvm/lib/Target/Hexagon/MCTargetDesc/HexagonInstPrinter.cpp @@ -43,7 +43,7 @@ } StringRef HexagonInstPrinter::getRegName(unsigned RegNo) const { - return getRegisterName(RegNo); + return StringRef(getRegisterName(RegNo)); } void HexagonInstPrinter::setExtender(MCInst const &MCI) { Index: llvm/lib/Target/Lanai/LanaiAsmPrinter.cpp =================================================================== --- llvm/lib/Target/Lanai/LanaiAsmPrinter.cpp +++ llvm/lib/Target/Lanai/LanaiAsmPrinter.cpp @@ -89,7 +89,7 @@ } case MachineOperand::MO_ExternalSymbol: - O << *GetExternalSymbolSymbol(MO.getSymbolName()); + O << *GetExternalSymbolSymbol(StringRef(MO.getSymbolName())); break; case MachineOperand::MO_JumpTableIndex: Index: llvm/lib/Target/Lanai/LanaiISelLowering.cpp =================================================================== --- llvm/lib/Target/Lanai/LanaiISelLowering.cpp +++ llvm/lib/Target/Lanai/LanaiISelLowering.cpp @@ -200,7 +200,7 @@ unsigned LanaiTargetLowering::getRegisterByName(const char *RegName, EVT /*VT*/, SelectionDAG & /*DAG*/) const { // Only unallocatable registers should be matched here. - unsigned Reg = StringSwitch(RegName) + unsigned Reg = StringSwitch(StringRef(RegName)) .Case("pc", Lanai::PC) .Case("sp", Lanai::SP) .Case("fp", Lanai::FP) Index: llvm/lib/Target/Lanai/LanaiMCInstLower.cpp =================================================================== --- llvm/lib/Target/Lanai/LanaiMCInstLower.cpp +++ llvm/lib/Target/Lanai/LanaiMCInstLower.cpp @@ -42,7 +42,7 @@ MCSymbol * LanaiMCInstLower::GetExternalSymbolSymbol(const MachineOperand &MO) const { - return Printer.GetExternalSymbolSymbol(MO.getSymbolName()); + return Printer.GetExternalSymbolSymbol(StringRef(MO.getSymbolName())); } MCSymbol *LanaiMCInstLower::GetJumpTableSymbol(const MachineOperand &MO) const { Index: llvm/lib/Target/MSP430/MSP430ISelDAGToDAG.cpp =================================================================== --- llvm/lib/Target/MSP430/MSP430ISelDAGToDAG.cpp +++ llvm/lib/Target/MSP430/MSP430ISelDAGToDAG.cpp @@ -149,7 +149,7 @@ AM.Disp += CP->getOffset(); //AM.SymbolFlags = CP->getTargetFlags(); } else if (ExternalSymbolSDNode *S = dyn_cast(N0)) { - AM.ES = S->getSymbol(); + AM.ES = S->getSymbol().data(); //AM.SymbolFlags = S->getTargetFlags(); } else if (JumpTableSDNode *J = dyn_cast(N0)) { AM.JT = J->getIndex(); @@ -267,7 +267,8 @@ Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i16, AM.Align, AM.Disp, 0/*AM.SymbolFlags*/); else if (AM.ES) - Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i16, 0/*AM.SymbolFlags*/); + Disp = CurDAG->getTargetExternalSymbol(StringRef(AM.ES), MVT::i16, + 0 /*AM.SymbolFlags*/); else if (AM.JT != -1) Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i16, 0/*AM.SymbolFlags*/); else if (AM.BlockAddr) Index: llvm/lib/Target/MSP430/MSP430ISelLowering.cpp =================================================================== --- llvm/lib/Target/MSP430/MSP430ISelLowering.cpp +++ llvm/lib/Target/MSP430/MSP430ISelLowering.cpp @@ -765,7 +765,7 @@ SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); - const char *Sym = cast(Op)->getSymbol(); + StringRef Sym = cast(Op)->getSymbol(); auto PtrVT = getPointerTy(DAG.getDataLayout()); SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT); Index: llvm/lib/Target/MSP430/MSP430MCInstLower.cpp =================================================================== --- llvm/lib/Target/MSP430/MSP430MCInstLower.cpp +++ llvm/lib/Target/MSP430/MSP430MCInstLower.cpp @@ -45,7 +45,7 @@ case 0: break; } - return Printer.GetExternalSymbolSymbol(MO.getSymbolName()); + return Printer.GetExternalSymbolSymbol(StringRef(MO.getSymbolName())); } MCSymbol *MSP430MCInstLower:: Index: llvm/lib/Target/Mips/Mips16HardFloat.cpp =================================================================== --- llvm/lib/Target/Mips/Mips16HardFloat.cpp +++ llvm/lib/Target/Mips/Mips16HardFloat.cpp @@ -350,26 +350,45 @@ // // Functions that are llvm intrinsics and don't need helpers. // -static const char *const IntrinsicInline[] = { - "fabs", "fabsf", - "llvm.ceil.f32", "llvm.ceil.f64", - "llvm.copysign.f32", "llvm.copysign.f64", - "llvm.cos.f32", "llvm.cos.f64", - "llvm.exp.f32", "llvm.exp.f64", - "llvm.exp2.f32", "llvm.exp2.f64", - "llvm.fabs.f32", "llvm.fabs.f64", - "llvm.floor.f32", "llvm.floor.f64", - "llvm.fma.f32", "llvm.fma.f64", - "llvm.log.f32", "llvm.log.f64", - "llvm.log10.f32", "llvm.log10.f64", - "llvm.nearbyint.f32", "llvm.nearbyint.f64", - "llvm.pow.f32", "llvm.pow.f64", - "llvm.powi.f32", "llvm.powi.f64", - "llvm.rint.f32", "llvm.rint.f64", - "llvm.round.f32", "llvm.round.f64", - "llvm.sin.f32", "llvm.sin.f64", - "llvm.sqrt.f32", "llvm.sqrt.f64", - "llvm.trunc.f32", "llvm.trunc.f64", +static const StringRef IntrinsicInline[] = { + "fabs", + "fabsf", + "llvm.ceil.f32", + "llvm.ceil.f64", + "llvm.copysign.f32", + "llvm.copysign.f64", + "llvm.cos.f32", + "llvm.cos.f64", + "llvm.exp.f32", + "llvm.exp.f64", + "llvm.exp2.f32", + "llvm.exp2.f64", + "llvm.fabs.f32", + "llvm.fabs.f64", + "llvm.floor.f32", + "llvm.floor.f64", + "llvm.fma.f32", + "llvm.fma.f64", + "llvm.log.f32", + "llvm.log.f64", + "llvm.log10.f32", + "llvm.log10.f64", + "llvm.nearbyint.f32", + "llvm.nearbyint.f64", + "llvm.pow.f32", + "llvm.pow.f64", + "llvm.powi.f32", + "llvm.powi.f64", + "llvm.rint.f32", + "llvm.rint.f64", + "llvm.round.f32", + "llvm.round.f64", + "llvm.sin.f32", + "llvm.sin.f64", + "llvm.sqrt.f32", + "llvm.sqrt.f64", + "llvm.trunc.f32", + "llvm.trunc.f64", }; static bool isIntrinsicInline(Function *F) { @@ -400,11 +419,10 @@ Type *T = RVal->getType(); FPReturnVariant RV = whichFPReturnVariant(T); if (RV == NoFPRet) continue; - static const char *const Helper[NoFPRet] = { - "__mips16_ret_sf", "__mips16_ret_df", "__mips16_ret_sc", - "__mips16_ret_dc" - }; - const char *Name = Helper[RV]; + static const StringRef Helper[NoFPRet] = { + "__mips16_ret_sf", "__mips16_ret_df", "__mips16_ret_sc", + "__mips16_ret_dc"}; + StringRef Name = Helper[RV]; AttributeSet A; Value *Params[] = {RVal}; Modified = true; Index: llvm/lib/Target/Mips/Mips16ISelLowering.cpp =================================================================== --- llvm/lib/Target/Mips/Mips16ISelLowering.cpp +++ llvm/lib/Target/Mips/Mips16ISelLowering.cpp @@ -254,7 +254,8 @@ assert((I == 0 || HardFloatLibCalls[I - 1] < HardFloatLibCalls[I]) && "Array not sorted!"); if (HardFloatLibCalls[I].Libcall != RTLIB::UNKNOWN_LIBCALL) - setLibcallName(HardFloatLibCalls[I].Libcall, HardFloatLibCalls[I].Name); + setLibcallName(HardFloatLibCalls[I].Libcall, + StringRef(HardFloatLibCalls[I].Name)); } setLibcallName(RTLIB::O_F64, "__mips16_unorddf2"); @@ -437,13 +438,13 @@ // bool LookupHelper = true; if (ExternalSymbolSDNode *S = dyn_cast(CLI.Callee)) { - Mips16Libcall Find = { RTLIB::UNKNOWN_LIBCALL, S->getSymbol() }; + Mips16Libcall Find = {RTLIB::UNKNOWN_LIBCALL, S->getSymbol().data()}; if (std::binary_search(std::begin(HardFloatLibCalls), std::end(HardFloatLibCalls), Find)) LookupHelper = false; else { - const char *Symbol = S->getSymbol(); + const char *Symbol = S->getSymbol().data(); Mips16IntrinsicHelperType IntrinsicFind = { Symbol, "" }; const Mips16HardFloatInfo::FuncSignature *Signature = Mips16HardFloatInfo::findFuncSignature(Symbol); @@ -500,12 +501,12 @@ unsigned V0Reg = Mips::V0; if (NeedMips16Helper) { RegsToPass.push_front(std::make_pair(V0Reg, Callee)); - JumpTarget = DAG.getExternalSymbol(Mips16HelperFunction, + JumpTarget = DAG.getExternalSymbol(StringRef(Mips16HelperFunction), getPointerTy(DAG.getDataLayout())); ExternalSymbolSDNode *S = cast(JumpTarget); JumpTarget = getAddrGlobal(S, CLI.DL, JumpTarget.getValueType(), DAG, MipsII::MO_GOT, Chain, - FuncInfo->callPtrInfo(S->getSymbol())); + FuncInfo->callPtrInfo(S->getSymbol().data())); } else RegsToPass.push_front(std::make_pair((unsigned)Mips::T9, Callee)); } Index: llvm/lib/Target/Mips/MipsCCState.cpp =================================================================== --- llvm/lib/Target/Mips/MipsCCState.cpp +++ llvm/lib/Target/Mips/MipsCCState.cpp @@ -14,8 +14,8 @@ using namespace llvm; /// This function returns true if CallSym is a long double emulation routine. -static bool isF128SoftLibCall(const char *CallSym) { - const char *const LibCalls[] = { +static bool isF128SoftLibCall(StringRef CallSym) { + const StringRef LibCalls[] = { "__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2", "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi", "__fixunstfti", "__floatditf", @@ -30,10 +30,8 @@ "sqrtl", "truncl"}; // Check that LibCalls is sorted alphabetically. - auto Comp = [](const char *S1, const char *S2) { return strcmp(S1, S2) < 0; }; - assert(std::is_sorted(std::begin(LibCalls), std::end(LibCalls), Comp)); - return std::binary_search(std::begin(LibCalls), std::end(LibCalls), - CallSym, Comp); + assert(std::is_sorted(std::begin(LibCalls), std::end(LibCalls))); + return std::binary_search(std::begin(LibCalls), std::end(LibCalls), CallSym); } /// This function returns true if Ty is fp128, {f128} or i128 which was Index: llvm/lib/Target/Mips/MipsISelLowering.cpp =================================================================== --- llvm/lib/Target/Mips/MipsISelLowering.cpp +++ llvm/lib/Target/Mips/MipsISelLowering.cpp @@ -428,9 +428,9 @@ if (ABI.IsO32()) { // These libcalls are not available in 32-bit. - setLibcallName(RTLIB::SHL_I128, nullptr); - setLibcallName(RTLIB::SRL_I128, nullptr); - setLibcallName(RTLIB::SRA_I128, nullptr); + setLibcallName(RTLIB::SHL_I128, StringRef()); + setLibcallName(RTLIB::SRL_I128, StringRef()); + setLibcallName(RTLIB::SRA_I128, StringRef()); } setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2); @@ -2841,7 +2841,7 @@ GlobalOrExternal = true; } else if (ExternalSymbolSDNode *S = dyn_cast(Callee)) { - const char *Sym = S->getSymbol(); + StringRef Sym = S->getSymbol(); if (!ABI.IsN64() && !IsPIC) // !N64 && static Callee = DAG.getTargetExternalSymbol( @@ -2849,11 +2849,11 @@ else if (LargeGOT) { Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16, MipsII::MO_CALL_LO16, Chain, - FuncInfo->callPtrInfo(Sym)); + FuncInfo->callPtrInfo(Sym.data())); IsCallReloc = true; } else { // N64 || PIC Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain, - FuncInfo->callPtrInfo(Sym)); + FuncInfo->callPtrInfo(Sym.data())); IsCallReloc = true; } @@ -4029,15 +4029,15 @@ // Named registers is expected to be fairly rare. For now, just support $28 // since the linux kernel uses it. if (Subtarget.isGP64bit()) { - unsigned Reg = StringSwitch(RegName) - .Case("$28", Mips::GP_64) - .Default(0); + unsigned Reg = StringSwitch(StringRef(RegName)) + .Case("$28", Mips::GP_64) + .Default(0); if (Reg) return Reg; } else { - unsigned Reg = StringSwitch(RegName) - .Case("$28", Mips::GP) - .Default(0); + unsigned Reg = StringSwitch(StringRef(RegName)) + .Case("$28", Mips::GP) + .Default(0); if (Reg) return Reg; } Index: llvm/lib/Target/Mips/MipsMCInstLower.cpp =================================================================== --- llvm/lib/Target/Mips/MipsMCInstLower.cpp +++ llvm/lib/Target/Mips/MipsMCInstLower.cpp @@ -135,7 +135,7 @@ break; case MachineOperand::MO_ExternalSymbol: - Symbol = AsmPrinter.GetExternalSymbolSymbol(MO.getSymbolName()); + Symbol = AsmPrinter.GetExternalSymbolSymbol(StringRef(MO.getSymbolName())); Offset += MO.getOffset(); break; Index: llvm/lib/Target/Mips/MipsMachineFunction.cpp =================================================================== --- llvm/lib/Target/Mips/MipsMachineFunction.cpp +++ llvm/lib/Target/Mips/MipsMachineFunction.cpp @@ -86,7 +86,8 @@ return IsISR && (FI == ISRDataRegFI[0] || FI == ISRDataRegFI[1]); } MachinePointerInfo MipsFunctionInfo::callPtrInfo(const char *ES) { - return MachinePointerInfo(MF.getPSVManager().getExternalSymbolCallEntry(ES)); + return MachinePointerInfo( + MF.getPSVManager().getExternalSymbolCallEntry(StringRef(ES))); } MachinePointerInfo MipsFunctionInfo::callPtrInfo(const GlobalValue *GV) { Index: llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp =================================================================== --- llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp +++ llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp @@ -270,7 +270,7 @@ MO.getMBB()->getSymbol(), OutContext)); break; case MachineOperand::MO_ExternalSymbol: - MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName())); + MCOp = GetSymbolRef(GetExternalSymbolSymbol(StringRef(MO.getSymbolName()))); break; case MachineOperand::MO_GlobalAddress: MCOp = GetSymbolRef(getSymbol(MO.getGlobal())); Index: llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp =================================================================== --- llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp +++ llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp @@ -1454,8 +1454,8 @@ SDVTList ProtoVTs = DAG.getVTList(MVT::Other, MVT::Glue); std::string Proto = getPrototype(DAG.getDataLayout(), retTy, Args, Outs, retAlignment, CS); - const char *ProtoStr = - nvTM->getManagedStrPool()->getManagedString(Proto.c_str())->c_str(); + StringRef ProtoStr = + *nvTM->getManagedStrPool()->getManagedString(Proto.c_str()); SDValue ProtoOps[] = { Chain, DAG.getTargetExternalSymbol(ProtoStr, MVT::i32), InFlag, }; @@ -2063,15 +2063,14 @@ std::string *SavedStr = nvTM->getManagedStrPool()->getManagedString(ParamSym.c_str()); - return DAG.getTargetExternalSymbol(SavedStr->c_str(), v); + return DAG.getTargetExternalSymbol(*SavedStr, v); } // Check to see if the kernel argument is image*_t or sampler_t static bool isImageOrSamplerVal(const Value *arg, const Module *context) { - static const char *const specialTypes[] = { "struct._image2d_t", - "struct._image3d_t", - "struct._sampler_t" }; + static const StringRef specialTypes[] = { + "struct._image2d_t", "struct._image3d_t", "struct._sampler_t"}; Type *Ty = arg->getType(); auto *PTy = dyn_cast(Ty); Index: llvm/lib/Target/NVPTX/NVPTXReplaceImageHandles.cpp =================================================================== --- llvm/lib/Target/NVPTX/NVPTXReplaceImageHandles.cpp +++ llvm/lib/Target/NVPTX/NVPTXReplaceImageHandles.cpp @@ -151,7 +151,7 @@ } assert(TexHandleDef.getOperand(6).isSymbol() && "Load is not a symbol!"); - StringRef Sym = TexHandleDef.getOperand(6).getSymbolName(); + StringRef Sym(TexHandleDef.getOperand(6).getSymbolName()); std::string ParamBaseName = MF.getName(); ParamBaseName += "_param_"; assert(Sym.startswith(ParamBaseName) && "Invalid symbol reference"); Index: llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp =================================================================== --- llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp +++ llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp @@ -1294,31 +1294,12 @@ } void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) { - static const char *const CPUDirectives[] = { - "", - "ppc", - "ppc440", - "ppc601", - "ppc602", - "ppc603", - "ppc7400", - "ppc750", - "ppc970", - "ppcA2", - "ppce500mc", - "ppce5500", - "power3", - "power4", - "power5", - "power5x", - "power6", - "power6x", - "power7", - // FIXME: why is power8 missing here? - "ppc64", - "ppc64le", - "power9" - }; + static const StringRef CPUDirectives[] = { + "", "ppc", "ppc440", "ppc601", "ppc602", "ppc603", "ppc7400", "ppc750", + "ppc970", "ppcA2", "ppce500mc", "ppce5500", "power3", "power4", "power5", + "power5x", "power6", "power6x", "power7", + // FIXME: why is power8 missing here? + "ppc64", "ppc64le", "power9"}; // Get the numerically largest directive. // FIXME: How should we merge darwin directives? Index: llvm/lib/Target/PowerPC/PPCISelLowering.cpp =================================================================== --- llvm/lib/Target/PowerPC/PPCISelLowering.cpp +++ llvm/lib/Target/PowerPC/PPCISelLowering.cpp @@ -863,9 +863,9 @@ if (!isPPC64) { // These libcalls are not available in 32-bit. - setLibcallName(RTLIB::SHL_I128, nullptr); - setLibcallName(RTLIB::SRL_I128, nullptr); - setLibcallName(RTLIB::SRA_I128, nullptr); + setLibcallName(RTLIB::SHL_I128, StringRef()); + setLibcallName(RTLIB::SRL_I128, StringRef()); + setLibcallName(RTLIB::SRA_I128, StringRef()); } setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); @@ -11917,12 +11917,13 @@ report_fatal_error("Invalid register global variable type"); bool is64Bit = isPPC64 && VT == MVT::i64; - unsigned Reg = StringSwitch(RegName) - .Case("r1", is64Bit ? PPC::X1 : PPC::R1) - .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) - .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : - (is64Bit ? PPC::X13 : PPC::R13)) - .Default(0); + unsigned Reg = + StringSwitch(StringRef(RegName)) + .Case("r1", is64Bit ? PPC::X1 : PPC::R1) + .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) + .Case("r13", + (!isPPC64 && isDarwinABI) ? 0 : (is64Bit ? PPC::X13 : PPC::R13)) + .Default(0); if (Reg) return Reg; Index: llvm/lib/Target/PowerPC/PPCLoopPreIncPrep.cpp =================================================================== --- llvm/lib/Target/PowerPC/PPCLoopPreIncPrep.cpp +++ llvm/lib/Target/PowerPC/PPCLoopPreIncPrep.cpp @@ -92,7 +92,7 @@ } char PPCLoopPreIncPrep::ID = 0; -static const char *name = "Prepare loop for pre-inc. addressing modes"; +static const char name[] = "Prepare loop for pre-inc. addressing modes"; INITIALIZE_PASS_BEGIN(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false) INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) Index: llvm/lib/Target/Sparc/SparcISelLowering.h =================================================================== --- llvm/lib/Target/Sparc/SparcISelLowering.h +++ llvm/lib/Target/Sparc/SparcISelLowering.h @@ -184,8 +184,7 @@ SDValue LowerF128_LibCallArg(SDValue Chain, ArgListTy &Args, SDValue Arg, const SDLoc &DL, SelectionDAG &DAG) const; - SDValue LowerF128Op(SDValue Op, SelectionDAG &DAG, - const char *LibFuncName, + SDValue LowerF128Op(SDValue Op, SelectionDAG &DAG, StringRef LibFuncName, unsigned numArgs) const; SDValue LowerF128Compare(SDValue LHS, SDValue RHS, unsigned &SPCC, const SDLoc &DL, SelectionDAG &DAG) const; Index: llvm/lib/Target/Sparc/SparcISelLowering.cpp =================================================================== --- llvm/lib/Target/Sparc/SparcISelLowering.cpp +++ llvm/lib/Target/Sparc/SparcISelLowering.cpp @@ -702,7 +702,7 @@ dyn_cast(Callee)) { const Function *Fn = DAG.getMachineFunction().getFunction(); const Module *M = Fn->getParent(); - const char *CalleeName = E->getSymbol(); + StringRef CalleeName = E->getSymbol(); CalleeFn = M->getFunction(CalleeName); } @@ -1015,16 +1015,40 @@ // this table could be generated automatically from RegInfo. unsigned SparcTargetLowering::getRegisterByName(const char* RegName, EVT VT, SelectionDAG &DAG) const { - unsigned Reg = StringSwitch(RegName) - .Case("i0", SP::I0).Case("i1", SP::I1).Case("i2", SP::I2).Case("i3", SP::I3) - .Case("i4", SP::I4).Case("i5", SP::I5).Case("i6", SP::I6).Case("i7", SP::I7) - .Case("o0", SP::O0).Case("o1", SP::O1).Case("o2", SP::O2).Case("o3", SP::O3) - .Case("o4", SP::O4).Case("o5", SP::O5).Case("o6", SP::O6).Case("o7", SP::O7) - .Case("l0", SP::L0).Case("l1", SP::L1).Case("l2", SP::L2).Case("l3", SP::L3) - .Case("l4", SP::L4).Case("l5", SP::L5).Case("l6", SP::L6).Case("l7", SP::L7) - .Case("g0", SP::G0).Case("g1", SP::G1).Case("g2", SP::G2).Case("g3", SP::G3) - .Case("g4", SP::G4).Case("g5", SP::G5).Case("g6", SP::G6).Case("g7", SP::G7) - .Default(0); + unsigned Reg = StringSwitch(StringRef(RegName)) + .Case("i0", SP::I0) + .Case("i1", SP::I1) + .Case("i2", SP::I2) + .Case("i3", SP::I3) + .Case("i4", SP::I4) + .Case("i5", SP::I5) + .Case("i6", SP::I6) + .Case("i7", SP::I7) + .Case("o0", SP::O0) + .Case("o1", SP::O1) + .Case("o2", SP::O2) + .Case("o3", SP::O3) + .Case("o4", SP::O4) + .Case("o5", SP::O5) + .Case("o6", SP::O6) + .Case("o7", SP::O7) + .Case("l0", SP::L0) + .Case("l1", SP::L1) + .Case("l2", SP::L2) + .Case("l3", SP::L3) + .Case("l4", SP::L4) + .Case("l5", SP::L5) + .Case("l6", SP::L6) + .Case("l7", SP::L7) + .Case("g0", SP::G0) + .Case("g1", SP::G1) + .Case("g2", SP::G2) + .Case("g3", SP::G3) + .Case("g4", SP::G4) + .Case("g5", SP::G5) + .Case("g6", SP::G6) + .Case("g7", SP::G7) + .Default(0); if (Reg) return Reg; @@ -1034,17 +1058,13 @@ // This functions returns true if CalleeName is a ABI function that returns // a long double (fp128). -static bool isFP128ABICall(const char *CalleeName) -{ - static const char *const ABICalls[] = - { "_Q_add", "_Q_sub", "_Q_mul", "_Q_div", - "_Q_sqrt", "_Q_neg", - "_Q_itoq", "_Q_stoq", "_Q_dtoq", "_Q_utoq", - "_Q_lltoq", "_Q_ulltoq", - nullptr - }; - for (const char * const *I = ABICalls; *I != nullptr; ++I) - if (strcmp(CalleeName, *I) == 0) +static bool isFP128ABICall(StringRef CalleeName) { + static const StringRef ABICalls[] = { + "_Q_add", "_Q_sub", "_Q_mul", "_Q_div", "_Q_sqrt", + "_Q_neg", "_Q_itoq", "_Q_stoq", "_Q_dtoq", "_Q_utoq", + "_Q_lltoq", "_Q_ulltoq", StringRef()}; + for (auto *I = ABICalls; !I->empty(); ++I) + if (CalleeName == *I) return true; return false; } @@ -1059,7 +1079,7 @@ dyn_cast(Callee)) { const Function *Fn = DAG.getMachineFunction().getFunction(); const Module *M = Fn->getParent(); - const char *CalleeName = E->getSymbol(); + StringRef CalleeName = E->getSymbol(); CalleeFn = M->getFunction(CalleeName); if (!CalleeFn && isFP128ABICall(CalleeName)) return 16; // Return sizeof(fp128) @@ -1643,9 +1663,9 @@ if (!Subtarget->is64Bit()) { // These libcalls are not available in 32-bit. - setLibcallName(RTLIB::SHL_I128, nullptr); - setLibcallName(RTLIB::SRL_I128, nullptr); - setLibcallName(RTLIB::SRA_I128, nullptr); + setLibcallName(RTLIB::SHL_I128, StringRef()); + setLibcallName(RTLIB::SRL_I128, StringRef()); + setLibcallName(RTLIB::SRA_I128, StringRef()); } if (!Subtarget->isV9()) { @@ -2153,17 +2173,16 @@ return Chain; } -SDValue -SparcTargetLowering::LowerF128Op(SDValue Op, SelectionDAG &DAG, - const char *LibFuncName, - unsigned numArgs) const { +SDValue SparcTargetLowering::LowerF128Op(SDValue Op, SelectionDAG &DAG, + StringRef LibFuncName, + unsigned numArgs) const { ArgListTy Args; MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); auto PtrVT = getPointerTy(DAG.getDataLayout()); - SDValue Callee = DAG.getExternalSymbol(LibFuncName, PtrVT); + SDValue Callee = DAG.getExternalSymbol(StringRef(LibFuncName), PtrVT); Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext()); Type *RetTyABI = RetTy; SDValue Chain = DAG.getEntryNode(); @@ -2231,7 +2250,7 @@ } auto PtrVT = getPointerTy(DAG.getDataLayout()); - SDValue Callee = DAG.getExternalSymbol(LibCall, PtrVT); + SDValue Callee = DAG.getExternalSymbol(StringRef(LibCall), PtrVT); Type *RetTy = Type::getInt32Ty(*DAG.getContext()); ArgListTy Args; SDValue Chain = DAG.getEntryNode(); @@ -2347,9 +2366,8 @@ // Expand f128 operations to fp128 abi calls. if (Op.getOperand(0).getValueType() == MVT::f128 && (!hasHardQuad || !TLI.isTypeLegal(VT))) { - const char *libName = TLI.getLibcallName(VT == MVT::i32 - ? RTLIB::FPTOSINT_F128_I32 - : RTLIB::FPTOSINT_F128_I64); + StringRef libName = TLI.getLibcallName( + VT == MVT::i32 ? RTLIB::FPTOSINT_F128_I32 : RTLIB::FPTOSINT_F128_I64); return TLI.LowerF128Op(Op, DAG, libName, 1); } @@ -2378,9 +2396,8 @@ // Expand f128 operations to fp128 ABI calls. if (Op.getValueType() == MVT::f128 && (!hasHardQuad || !TLI.isTypeLegal(OpVT))) { - const char *libName = TLI.getLibcallName(OpVT == MVT::i32 - ? RTLIB::SINTTOFP_I32_F128 - : RTLIB::SINTTOFP_I64_F128); + StringRef libName = TLI.getLibcallName( + OpVT == MVT::i32 ? RTLIB::SINTTOFP_I32_F128 : RTLIB::SINTTOFP_I64_F128); return TLI.LowerF128Op(Op, DAG, libName, 1); } Index: llvm/lib/Target/Sparc/SparcMCInstLower.cpp =================================================================== --- llvm/lib/Target/Sparc/SparcMCInstLower.cpp +++ llvm/lib/Target/Sparc/SparcMCInstLower.cpp @@ -50,7 +50,7 @@ break; case MachineOperand::MO_ExternalSymbol: - Symbol = AP.GetExternalSymbolSymbol(MO.getSymbolName()); + Symbol = AP.GetExternalSymbolSymbol(StringRef(MO.getSymbolName())); break; case MachineOperand::MO_ConstantPoolIndex: Index: llvm/lib/Target/SystemZ/SystemZMCInstLower.cpp =================================================================== --- llvm/lib/Target/SystemZ/SystemZMCInstLower.cpp +++ llvm/lib/Target/SystemZ/SystemZMCInstLower.cpp @@ -49,7 +49,7 @@ break; case MachineOperand::MO_ExternalSymbol: - Symbol = AsmPrinter.GetExternalSymbolSymbol(MO.getSymbolName()); + Symbol = AsmPrinter.GetExternalSymbolSymbol(StringRef(MO.getSymbolName())); break; case MachineOperand::MO_JumpTableIndex: Index: llvm/lib/Target/Target.cpp =================================================================== --- llvm/lib/Target/Target.cpp +++ llvm/lib/Target/Target.cpp @@ -54,7 +54,7 @@ } LLVMTargetDataRef LLVMCreateTargetData(const char *StringRep) { - return wrap(new DataLayout(StringRep)); + return wrap(new DataLayout(StringRef(StringRep))); } void LLVMDisposeTargetData(LLVMTargetDataRef TD) { Index: llvm/lib/Target/TargetMachineC.cpp =================================================================== --- llvm/lib/Target/TargetMachineC.cpp +++ llvm/lib/Target/TargetMachineC.cpp @@ -58,7 +58,7 @@ } LLVMTargetRef LLVMGetTargetFromName(const char *Name) { - StringRef NameRef = Name; + StringRef NameRef(Name); auto I = find_if(TargetRegistry::targets(), [&](const Target &T) { return T.getName() == NameRef; }); return I != TargetRegistry::targets().end() ? wrap(&*I) : nullptr; @@ -138,8 +138,8 @@ } TargetOptions opt; - return wrap(unwrap(T)->createTargetMachine(Triple, CPU, Features, opt, RM, - CM, OL)); + return wrap(unwrap(T)->createTargetMachine( + StringRef(Triple), StringRef(CPU), StringRef(Features), opt, RM, CM, OL)); } void LLVMDisposeTargetMachine(LLVMTargetMachineRef T) { delete unwrap(T); } @@ -210,7 +210,7 @@ LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M, char* Filename, LLVMCodeGenFileType codegen, char** ErrorMessage) { std::error_code EC; - raw_fd_ostream dest(Filename, EC, sys::fs::F_None); + raw_fd_ostream dest(StringRef(Filename), EC, sys::fs::F_None); if (EC) { *ErrorMessage = strdup(EC.message().c_str()); return true; Index: llvm/lib/Target/TargetRecip.cpp =================================================================== --- llvm/lib/Target/TargetRecip.cpp +++ llvm/lib/Target/TargetRecip.cpp @@ -27,15 +27,9 @@ // the key strings for queries and command-line inputs. // In addition, the command-line interface recognizes the global parameters // "all", "none", and "default". -static const char *const RecipOps[] = { - "divd", - "divf", - "vec-divd", - "vec-divf", - "sqrtd", - "sqrtf", - "vec-sqrtd", - "vec-sqrtf", +static StringRef RecipOps[] = { + "divd", "divf", "vec-divd", "vec-divf", + "sqrtd", "sqrtf", "vec-sqrtd", "vec-sqrtf", }; /// All operations are disabled by default and refinement steps are set to zero. Index: llvm/lib/Target/X86/AsmParser/X86AsmParser.cpp =================================================================== --- llvm/lib/Target/X86/AsmParser/X86AsmParser.cpp +++ llvm/lib/Target/X86/AsmParser/X86AsmParser.cpp @@ -1924,14 +1924,14 @@ !getLexer().getTok().getIdentifier().startswith("to")) return !TokError("Expected 1to at this point"); // Recognize only reasonable suffixes. - const char *BroadcastPrimitive = - StringSwitch(getLexer().getTok().getIdentifier()) - .Case("to2", "{1to2}") - .Case("to4", "{1to4}") - .Case("to8", "{1to8}") - .Case("to16", "{1to16}") - .Default(nullptr); - if (!BroadcastPrimitive) + StringRef BroadcastPrimitive( + StringSwitch(getLexer().getTok().getIdentifier()) + .Case("to2", "{1to2}") + .Case("to4", "{1to4}") + .Case("to8", "{1to8}") + .Case("to16", "{1to16}") + .Default(nullptr)); + if (BroadcastPrimitive.empty()) return !TokError("Invalid memory broadcast primitive."); Parser.Lex(); // Eat "toN" of 1toN if (!getLexer().is(AsmToken::RCurly)) @@ -2359,11 +2359,11 @@ bool IsFp = Name == "fsub" || Name == "fdiv" || Name == "fsubr" || Name == "fdivr"; if (IsFp && Operands.size() == 1) { - const char *Repl = StringSwitch(Name) - .Case("fsub", "fsubp") - .Case("fdiv", "fdivp") - .Case("fsubr", "fsubrp") - .Case("fdivr", "fdivrp"); + StringRef Repl(StringSwitch(Name) + .Case("fsub", "fsubp") + .Case("fdiv", "fdivp") + .Case("fsubr", "fsubrp") + .Case("fdivr", "fdivrp")); static_cast(*Operands[0]).setTokenValue(Repl); } @@ -2584,24 +2584,24 @@ // FIXME: This should be replaced with a real .td file alias mechanism. // Also, MatchInstructionImpl should actually *do* the EmitInstruction // call. - const char *Repl = StringSwitch(Op.getToken()) - .Case("finit", "fninit") - .Case("fsave", "fnsave") - .Case("fstcw", "fnstcw") - .Case("fstcww", "fnstcw") - .Case("fstenv", "fnstenv") - .Case("fstsw", "fnstsw") - .Case("fstsww", "fnstsw") - .Case("fclex", "fnclex") - .Default(nullptr); - if (Repl) { - MCInst Inst; - Inst.setOpcode(X86::WAIT); - Inst.setLoc(IDLoc); - if (!MatchingInlineAsm) - EmitInstruction(Inst, Operands, Out); - Operands[0] = X86Operand::CreateToken(Repl, IDLoc); - } + StringRef Repl(StringSwitch(Op.getToken()) + .Case("finit", "fninit") + .Case("fsave", "fnsave") + .Case("fstcw", "fnstcw") + .Case("fstcww", "fnstcw") + .Case("fstenv", "fnstenv") + .Case("fstsw", "fnstsw") + .Case("fstsww", "fnstsw") + .Case("fclex", "fnclex") + .Default(nullptr)); + if (Repl.empty()) + return; + MCInst Inst; + Inst.setOpcode(X86::WAIT); + Inst.setLoc(IDLoc); + if (!MatchingInlineAsm) + EmitInstruction(Inst, Operands, Out); + Operands[0] = X86Operand::CreateToken(Repl, IDLoc); } bool X86AsmParser::ErrorMissingFeature(SMLoc IDLoc, uint64_t ErrorInfo, @@ -2816,8 +2816,8 @@ // Allow some instructions to have implicitly pointer-sized operands. This is // compatible with gas. if (UnsizedMemOp) { - static const char *const PtrSizedInstrs[] = {"call", "jmp", "push"}; - for (const char *Instr : PtrSizedInstrs) { + static StringRef PtrSizedInstrs[] = {"call", "jmp", "push"}; + for (StringRef Instr : PtrSizedInstrs) { if (Mnemonic == Instr) { UnsizedMemOp->Mem.Size = getPointerWidth(); break; Index: llvm/lib/Target/X86/X86AsmPrinter.cpp =================================================================== --- llvm/lib/Target/X86/X86AsmPrinter.cpp +++ llvm/lib/Target/X86/X86AsmPrinter.cpp @@ -613,8 +613,8 @@ } if (TT.isKnownWindowsMSVCEnvironment() && MMI->usesVAFloatArgument()) { - StringRef SymbolName = - (TT.getArch() == Triple::x86_64) ? "_fltused" : "__fltused"; + StringRef SymbolName((TT.getArch() == Triple::x86_64) ? "_fltused" + : "__fltused"); MCSymbol *S = MMI->getContext().getOrCreateSymbol(SymbolName); OutStreamer->EmitSymbolAttribute(S, MCSA_Global); } Index: llvm/lib/Target/X86/X86FrameLowering.cpp =================================================================== --- llvm/lib/Target/X86/X86FrameLowering.cpp +++ llvm/lib/Target/X86/X86FrameLowering.cpp @@ -465,12 +465,12 @@ void X86FrameLowering::inlineStackProbe(MachineFunction &MF, MachineBasicBlock &PrologMBB) const { - const StringRef ChkStkStubSymbol = "__chkstk_stub"; + StringRef ChkStkStubSymbol = "__chkstk_stub"; MachineInstr *ChkStkStub = nullptr; for (MachineInstr &MI : PrologMBB) { if (MI.isCall() && MI.getOperand(0).isSymbol() && - ChkStkStubSymbol == MI.getOperand(0).getSymbolName()) { + ChkStkStubSymbol == StringRef(MI.getOperand(0).getSymbolName())) { ChkStkStub = &MI; break; } @@ -2384,9 +2384,8 @@ if (!HiPELiteralsMD) report_fatal_error( "Can't generate HiPE prologue without runtime parameters"); - const unsigned HipeLeafWords - = getHiPELiteral(HiPELiteralsMD, - Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS"); + StringRef WhichWords(Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS"); + const unsigned HipeLeafWords = getHiPELiteral(HiPELiteralsMD, WhichWords); const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5; const unsigned Guaranteed = HipeLeafWords * SlotSize; unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ? Index: llvm/lib/Target/X86/X86ISelDAGToDAG.cpp =================================================================== --- llvm/lib/Target/X86/X86ISelDAGToDAG.cpp +++ llvm/lib/Target/X86/X86ISelDAGToDAG.cpp @@ -65,7 +65,7 @@ const GlobalValue *GV; const Constant *CP; const BlockAddress *BlockAddr; - const char *ES; + StringRef ES; MCSymbol *MCSym; int JT; unsigned Align; // CP alignment. @@ -73,11 +73,11 @@ X86ISelAddressMode() : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0), - Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr), + Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {} bool hasSymbolicDisplacement() const { - return GV != nullptr || CP != nullptr || ES != nullptr || + return GV != nullptr || CP != nullptr || !ES.empty() || MCSym != nullptr || JT != -1 || BlockAddr != nullptr; } @@ -128,7 +128,7 @@ dbgs() << "nul"; dbgs() << '\n' << "ES "; - if (ES) + if (!ES.empty()) dbgs() << ES; else dbgs() << "nul"; @@ -261,7 +261,7 @@ else if (AM.CP) Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp, AM.SymbolFlags); - else if (AM.ES) { + else if (!AM.ES.empty()) { assert(!AM.Disp && "Non-zero displacement is ignored with ES."); Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags); } else if (AM.MCSym) { @@ -687,7 +687,7 @@ bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM) { // Cannot combine ExternalSymbol displacements with integer offsets. - if (Offset != 0 && (AM.ES || AM.MCSym)) + if (Offset != 0 && (!AM.ES.empty() || AM.MCSym)) return true; int64_t Val = AM.Disp + Offset; CodeModel::Model M = TM.getCodeModel(); @@ -1122,7 +1122,7 @@ // FIXME: JumpTable and ExternalSymbol address currently don't like // displacements. It isn't very important, but this should be fixed for // consistency. - if (!(AM.ES || AM.MCSym) && AM.JT != -1) + if (!(!AM.ES.empty() || AM.MCSym) && AM.JT != -1) return true; if (ConstantSDNode *Cst = dyn_cast(N)) Index: llvm/lib/Target/X86/X86ISelLowering.cpp =================================================================== --- llvm/lib/Target/X86/X86ISelLowering.cpp +++ llvm/lib/Target/X86/X86ISelLowering.cpp @@ -1622,9 +1622,9 @@ if (!Subtarget.is64Bit()) { // These libcalls are not available in 32-bit. - setLibcallName(RTLIB::SHL_I128, nullptr); - setLibcallName(RTLIB::SRL_I128, nullptr); - setLibcallName(RTLIB::SRA_I128, nullptr); + setLibcallName(RTLIB::SHL_I128, StringRef()); + setLibcallName(RTLIB::SRL_I128, StringRef()); + setLibcallName(RTLIB::SRA_I128, StringRef()); } // Combine sin / cos into one node or libcall if possible. @@ -13099,7 +13099,7 @@ SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { - const char *Sym = cast(Op)->getSymbol(); + StringRef Sym = cast(Op)->getSymbol(); // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the // global base reg. @@ -15230,7 +15230,7 @@ unsigned &RefinementSteps, bool &UseOneConstNR) const { EVT VT = Op.getValueType(); - const char *RecipOp; + StringRef RecipOp; // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps. // TODO: Add support for AVX512 (v16f32). @@ -15262,7 +15262,7 @@ DAGCombinerInfo &DCI, unsigned &RefinementSteps) const { EVT VT = Op.getValueType(); - const char *RecipOp; + StringRef RecipOp; // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps. // TODO: Add support for AVX512 (v16f32). @@ -19013,12 +19013,12 @@ const TargetFrameLowering &TFI = *Subtarget.getFrameLowering(); const MachineFunction &MF = DAG.getMachineFunction(); - unsigned Reg = StringSwitch(RegName) - .Case("esp", X86::ESP) - .Case("rsp", X86::RSP) - .Case("ebp", X86::EBP) - .Case("rbp", X86::RBP) - .Default(0); + unsigned Reg = StringSwitch(StringRef(RegName)) + .Case("esp", X86::ESP) + .Case("rsp", X86::RSP) + .Case("ebp", X86::EBP) + .Case("rbp", X86::RBP) + .Default(0); if (Reg == X86::EBP || Reg == X86::RBP) { if (!TFI.hasFP(MF)) @@ -21689,7 +21689,7 @@ // Only optimize x86_64 for now. i386 is a bit messy. For f32, // the small struct {f32, f32} is returned in (eax, edx). For f64, // the results are returned via SRet in memory. - const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret"; + StringRef LibcallName(isF64 ? "__sincos_stret" : "__sincosf_stret"); const TargetLowering &TLI = DAG.getTargetLoweringInfo(); SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout())); @@ -32049,7 +32049,7 @@ //===----------------------------------------------------------------------===// // Helper to match a string separated by whitespace. -static bool matchAsm(StringRef S, ArrayRef Pieces) { +static bool matchAsm(StringRef S, ArrayRef Pieces) { S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace. for (StringRef Piece : Pieces) { Index: llvm/lib/Target/X86/X86MCInstLower.cpp =================================================================== --- llvm/lib/Target/X86/X86MCInstLower.cpp +++ llvm/lib/Target/X86/X86MCInstLower.cpp @@ -753,7 +753,7 @@ EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX)); } - StringRef name = is64Bits ? "__tls_get_addr" : "___tls_get_addr"; + StringRef name(is64Bits ? "__tls_get_addr" : "___tls_get_addr"); MCSymbol *tlsGetAddr = context.getOrCreateSymbol(name); const MCSymbolRefExpr *tlsRef = MCSymbolRefExpr::create(tlsGetAddr, @@ -1203,7 +1203,7 @@ // and they actually agree on register naming here. Ultimately, this is // a comment, and so its OK if it isn't perfect. auto GetRegisterName = [](unsigned RegNum) -> StringRef { - return X86ATTInstPrinter::getRegisterName(RegNum); + return StringRef(X86ATTInstPrinter::getRegisterName(RegNum)); }; // TODO: Add support for specifying an AVX512 style mask register in the comment. Index: llvm/lib/Target/X86/X86SelectionDAGInfo.cpp =================================================================== --- llvm/lib/Target/X86/X86SelectionDAGInfo.cpp +++ llvm/lib/Target/X86/X86SelectionDAGInfo.cpp @@ -71,8 +71,11 @@ // Check to see if there is a specialized entry-point for memory zeroing. ConstantSDNode *V = dyn_cast(Src); - if (const char *bzeroEntry = V && - V->isNullValue() ? Subtarget.getBZeroEntry() : nullptr) { + StringRef bzeroEntry; + if (V && V->isNullValue()) + bzeroEntry = Subtarget.getBZeroEntry(); + + if (!bzeroEntry.empty()) { const TargetLowering &TLI = DAG.getTargetLoweringInfo(); EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout()); Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); Index: llvm/lib/Target/X86/X86Subtarget.h =================================================================== --- llvm/lib/Target/X86/X86Subtarget.h +++ llvm/lib/Target/X86/X86Subtarget.h @@ -589,7 +589,7 @@ /// the current subtarget and it is considered prefereable over /// memset with zero passed as the second argument. Otherwise it /// returns null. - const char *getBZeroEntry() const; + StringRef getBZeroEntry() const; /// This function returns true if the target has sincos() routine in its /// compiler runtime or math libraries. Index: llvm/lib/Target/X86/X86Subtarget.cpp =================================================================== --- llvm/lib/Target/X86/X86Subtarget.cpp +++ llvm/lib/Target/X86/X86Subtarget.cpp @@ -143,13 +143,13 @@ /// the non-standard bzero function, if such a function exists on the /// current subtarget and it is considered preferable over memset with zero /// passed as the second argument. Otherwise it returns null. -const char *X86Subtarget::getBZeroEntry() const { +StringRef X86Subtarget::getBZeroEntry() const { // Darwin 10 has a __bzero entry point for this purpose. if (getTargetTriple().isMacOSX() && !getTargetTriple().isMacOSXVersionLT(10, 6)) return "__bzero"; - return nullptr; + return StringRef(); } bool X86Subtarget::hasSinCos() const { Index: llvm/lib/Target/X86/X86TargetMachine.cpp =================================================================== --- llvm/lib/Target/X86/X86TargetMachine.cpp +++ llvm/lib/Target/X86/X86TargetMachine.cpp @@ -200,7 +200,7 @@ // If the soft float attribute is set on the function turn on the soft float // subtarget feature. if (SoftFloat) - Key += FS.empty() ? "+soft-float" : ",+soft-float"; + Key += StringRef(FS.empty() ? "+soft-float" : ",+soft-float"); FS = Key.substr(CPU.size()); Index: llvm/lib/Target/X86/X86WinEHState.cpp =================================================================== --- llvm/lib/Target/X86/X86WinEHState.cpp +++ llvm/lib/Target/X86/X86WinEHState.cpp @@ -352,7 +352,8 @@ linkExceptionRegistration(Builder, PersonalityFn); SehLongjmpUnwind = TheModule->getOrInsertFunction( - UseStackGuard ? "_seh_longjmp_unwind4" : "_seh_longjmp_unwind", + StringRef(UseStackGuard ? "_seh_longjmp_unwind4" + : "_seh_longjmp_unwind"), FunctionType::get(Type::getVoidTy(TheModule->getContext()), Int8PtrType, /*isVarArg=*/false)); cast(SehLongjmpUnwind->stripPointerCasts()) Index: llvm/lib/Target/XCore/XCoreMCInstLower.cpp =================================================================== --- llvm/lib/Target/XCore/XCoreMCInstLower.cpp +++ llvm/lib/Target/XCore/XCoreMCInstLower.cpp @@ -48,7 +48,7 @@ Offset += MO.getOffset(); break; case MachineOperand::MO_ExternalSymbol: - Symbol = Printer.GetExternalSymbolSymbol(MO.getSymbolName()); + Symbol = Printer.GetExternalSymbolSymbol(StringRef(MO.getSymbolName())); Offset += MO.getOffset(); break; case MachineOperand::MO_JumpTableIndex: Index: llvm/lib/Transforms/Coroutines/Coroutines.cpp =================================================================== --- llvm/lib/Transforms/Coroutines/Coroutines.cpp +++ llvm/lib/Transforms/Coroutines/Coroutines.cpp @@ -102,11 +102,11 @@ #ifndef NDEBUG static bool isCoroutineIntrinsicName(StringRef Name) { // NOTE: Must be sorted! - static const char *const CoroIntrinsics[] = { - "llvm.coro.alloc", "llvm.coro.begin", "llvm.coro.destroy", - "llvm.coro.done", "llvm.coro.end", "llvm.coro.frame", - "llvm.coro.free", "llvm.coro.id", "llvm.coro.param", - "llvm.coro.promise", "llvm.coro.resume", "llvm.coro.save", + static StringRef const CoroIntrinsics[] = { + "llvm.coro.alloc", "llvm.coro.begin", "llvm.coro.destroy", + "llvm.coro.done", "llvm.coro.end", "llvm.coro.frame", + "llvm.coro.free", "llvm.coro.id", "llvm.coro.param", + "llvm.coro.promise", "llvm.coro.resume", "llvm.coro.save", "llvm.coro.size", "llvm.coro.subfn.addr", "llvm.coro.suspend", }; return Intrinsic::lookupLLVMIntrinsicByName(CoroIntrinsics, Name) != -1; Index: llvm/lib/Transforms/IPO/LowerTypeTests.cpp =================================================================== --- llvm/lib/Transforms/IPO/LowerTypeTests.cpp +++ llvm/lib/Transforms/IPO/LowerTypeTests.cpp @@ -777,9 +777,9 @@ auto JumpTable = new GlobalVariable(M, JumpTableType, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr); - JumpTable->setSection(ObjectFormat == Triple::MachO - ? "__TEXT,__text,regular,pure_instructions" - : ".text"); + JumpTable->setSection(StringRef( + ObjectFormat == Triple::MachO ? "__TEXT,__text,regular,pure_instructions" + : ".text")); lowerTypeTestCalls(TypeIds, JumpTable, GlobalLayout); // Build aliases pointing to offsets into the jump table, and replace Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp =================================================================== --- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp +++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp @@ -89,47 +89,44 @@ static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3; static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E; -static const char *const kAsanModuleCtorName = "asan.module_ctor"; -static const char *const kAsanModuleDtorName = "asan.module_dtor"; +static const char kAsanModuleCtorName[] = "asan.module_ctor"; +static const char kAsanModuleDtorName[] = "asan.module_dtor"; static const uint64_t kAsanCtorAndDtorPriority = 1; -static const char *const kAsanReportErrorTemplate = "__asan_report_"; -static const char *const kAsanRegisterGlobalsName = "__asan_register_globals"; -static const char *const kAsanUnregisterGlobalsName = - "__asan_unregister_globals"; -static const char *const kAsanRegisterImageGlobalsName = - "__asan_register_image_globals"; -static const char *const kAsanUnregisterImageGlobalsName = - "__asan_unregister_image_globals"; -static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init"; -static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init"; -static const char *const kAsanInitName = "__asan_init"; -static const char *const kAsanVersionCheckName = - "__asan_version_mismatch_check_v8"; -static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp"; -static const char *const kAsanPtrSub = "__sanitizer_ptr_sub"; -static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return"; +static const char kAsanReportErrorTemplate[] = "__asan_report_"; +static const char kAsanRegisterGlobalsName[] = "__asan_register_globals"; +static const char kAsanUnregisterGlobalsName[] = "__asan_unregister_globals"; +static const char kAsanRegisterImageGlobalsName[] = + "__asan_register_image_globals"; +static const char kAsanUnregisterImageGlobalsName[] = + "__asan_unregister_image_globals"; +static const char kAsanPoisonGlobalsName[] = "__asan_before_dynamic_init"; +static const char kAsanUnpoisonGlobalsName[] = "__asan_after_dynamic_init"; +static const char kAsanInitName[] = "__asan_init"; +static const char kAsanVersionCheckName[] = "__asan_version_mismatch_check_v8"; +static const char kAsanPtrCmp[] = "__sanitizer_ptr_cmp"; +static const char kAsanPtrSub[] = "__sanitizer_ptr_sub"; +static const char kAsanHandleNoReturnName[] = "__asan_handle_no_return"; static const int kMaxAsanStackMallocSizeClass = 10; -static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_"; -static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_"; -static const char *const kAsanGenPrefix = "__asan_gen_"; -static const char *const kODRGenPrefix = "__odr_asan_gen_"; -static const char *const kSanCovGenPrefix = "__sancov_gen_"; -static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_"; -static const char *const kAsanPoisonStackMemoryName = - "__asan_poison_stack_memory"; -static const char *const kAsanUnpoisonStackMemoryName = +static const char kAsanStackMallocNameTemplate[] = "__asan_stack_malloc_"; +static const char kAsanStackFreeNameTemplate[] = "__asan_stack_free_"; +static const char kAsanGenPrefix[] = "__asan_gen_"; +static const char kODRGenPrefix[] = "__odr_asan_gen_"; +static const char kSanCovGenPrefix[] = "__sancov_gen_"; +static const char kAsanSetShadowPrefix[] = "__asan_set_shadow_"; +static const char kAsanPoisonStackMemoryName[] = "__asan_poison_stack_memory"; +static const char kAsanUnpoisonStackMemoryName[] = "__asan_unpoison_stack_memory"; -static const char *const kAsanGlobalsRegisteredFlagName = +static const char kAsanGlobalsRegisteredFlagName[] = "__asan_globals_registered"; -static const char *const kAsanOptionDetectUseAfterReturn = +static const char kAsanOptionDetectUseAfterReturn[] = "__asan_option_detect_stack_use_after_return"; -static const char *const kAsanShadowMemoryDynamicAddress = +static const char kAsanShadowMemoryDynamicAddress[] = "__asan_shadow_memory_dynamic_address"; -static const char *const kAsanAllocaPoison = "__asan_alloca_poison"; -static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison"; +static const char kAsanAllocaPoison[] = "__asan_alloca_poison"; +static const char kAsanAllocasUnpoison[] = "__asan_allocas_unpoison"; // Accesses sizes are powers of two: 1, 2, 4, 8, 16. static const size_t kNumberOfAccessSizes = 5; Index: llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp =================================================================== --- llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp +++ llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp @@ -75,7 +75,7 @@ // External symbol to be used when generating the shadow address for // architectures with multiple VMAs. Instead of using a constant integer // the runtime will set the external mask based on the VMA range. -static const char *const kDFSanExternShadowPtrMask = "__dfsan_shadow_ptr_mask"; +static const char kDFSanExternShadowPtrMask[] = "__dfsan_shadow_ptr_mask"; // The -dfsan-preserve-alignment flag controls whether this pass assumes that // alignment requirements provided by the input IR are correct. For example, Index: llvm/lib/Transforms/Instrumentation/EfficiencySanitizer.cpp =================================================================== --- llvm/lib/Transforms/Instrumentation/EfficiencySanitizer.cpp +++ llvm/lib/Transforms/Instrumentation/EfficiencySanitizer.cpp @@ -86,14 +86,14 @@ "Number of accesses assumed to be intra-cache-line"); static const uint64_t EsanCtorAndDtorPriority = 0; -static const char *const EsanModuleCtorName = "esan.module_ctor"; -static const char *const EsanModuleDtorName = "esan.module_dtor"; -static const char *const EsanInitName = "__esan_init"; -static const char *const EsanExitName = "__esan_exit"; +static const char EsanModuleCtorName[] = "esan.module_ctor"; +static const char EsanModuleDtorName[] = "esan.module_dtor"; +static const char EsanInitName[] = "__esan_init"; +static const char EsanExitName[] = "__esan_exit"; // We need to specify the tool to the runtime earlier than // the ctor is called in some cases, so we set a global variable. -static const char *const EsanWhichToolName = "__esan_which_tool"; +static const char EsanWhichToolName[] = "__esan_which_tool"; // We must keep these Shadow* constants consistent with the esan runtime. // FIXME: Try to place these shadow constants, the names of the __esan_* Index: llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp =================================================================== --- llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp +++ llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp @@ -196,8 +196,8 @@ cl::desc("Place MSan constructors in comdat sections"), cl::Hidden, cl::init(false)); -static const char *const kMsanModuleCtorName = "msan.module_ctor"; -static const char *const kMsanInitName = "__msan_init"; +static const char kMsanModuleCtorName[] = "msan.module_ctor"; +static const char kMsanInitName[] = "__msan_init"; namespace { @@ -421,8 +421,8 @@ // Create the callback. // FIXME: this function should have "Cold" calling conv, // which is not yet implemented. - StringRef WarningFnName = ClKeepGoing ? "__msan_warning" - : "__msan_warning_noreturn"; + StringRef WarningFnName(ClKeepGoing ? "__msan_warning" + : "__msan_warning_noreturn"); WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr); for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes; Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp =================================================================== --- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp +++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp @@ -56,32 +56,28 @@ #define DEBUG_TYPE "sancov" -static const char *const SanCovModuleInitName = "__sanitizer_cov_module_init"; -static const char *const SanCovName = "__sanitizer_cov"; -static const char *const SanCovWithCheckName = "__sanitizer_cov_with_check"; -static const char *const SanCovIndirCallName = "__sanitizer_cov_indir_call16"; -static const char *const SanCovTracePCIndirName = - "__sanitizer_cov_trace_pc_indir"; -static const char *const SanCovTraceEnterName = - "__sanitizer_cov_trace_func_enter"; -static const char *const SanCovTraceBBName = - "__sanitizer_cov_trace_basic_block"; -static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc"; -static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1"; -static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2"; -static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4"; -static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8"; -static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4"; -static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8"; -static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep"; -static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch"; -static const char *const SanCovModuleCtorName = "sancov.module_ctor"; +static const char SanCovModuleInitName[] = "__sanitizer_cov_module_init"; +static const char SanCovName[] = "__sanitizer_cov"; +static const char SanCovWithCheckName[] = "__sanitizer_cov_with_check"; +static const char SanCovIndirCallName[] = "__sanitizer_cov_indir_call16"; +static const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir"; +static const char SanCovTraceEnterName[] = "__sanitizer_cov_trace_func_enter"; +static const char SanCovTraceBBName[] = "__sanitizer_cov_trace_basic_block"; +static const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc"; +static const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1"; +static const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2"; +static const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4"; +static const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8"; +static const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4"; +static const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8"; +static const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep"; +static const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch"; +static const char SanCovModuleCtorName[] = "sancov.module_ctor"; static const uint64_t SanCtorAndDtorPriority = 2; -static const char *const SanCovTracePCGuardSection = "__sancov_guards"; -static const char *const SanCovTracePCGuardName = - "__sanitizer_cov_trace_pc_guard"; -static const char *const SanCovTracePCGuardInitName = +static const char SanCovTracePCGuardSection[] = "__sancov_guards"; +static const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard"; +static const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init"; static cl::opt ClCoverageLevel( Index: llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp =================================================================== --- llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp +++ llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp @@ -75,8 +75,8 @@ STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads"); STATISTIC(NumOmittedNonCaptured, "Number of accesses ignored due to capturing"); -static const char *const kTsanModuleCtorName = "tsan.module_ctor"; -static const char *const kTsanInitName = "__tsan_init"; +static const char kTsanModuleCtorName[] = "tsan.module_ctor"; +static const char kTsanInitName[] = "__tsan_init"; namespace { Index: llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp =================================================================== --- llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp +++ llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp @@ -79,7 +79,7 @@ static cl::opt SkipProfitabilityChecks("irce-skip-profitability-checks", cl::Hidden, cl::init(false)); -static const char *ClonedLoopTag = "irce.loop.clone"; +static const char ClonedLoopTag[] = "irce.loop.clone"; #define DEBUG_TYPE "irce" Index: llvm/lib/Transforms/Scalar/LoopInterchange.cpp =================================================================== --- llvm/lib/Transforms/Scalar/LoopInterchange.cpp +++ llvm/lib/Transforms/Scalar/LoopInterchange.cpp @@ -117,8 +117,8 @@ // Track Output, Flow, and Anti dependencies. if (auto D = DI->depends(Src, Dst, true)) { assert(D->isOrdered() && "Expected an output, flow or anti dep."); - DEBUG(StringRef DepType = - D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output"; + DEBUG(StringRef DepType(D->isFlow() ? "flow" + : D->isAnti() ? "anti" : "output"); dbgs() << "Found " << DepType << " dependency between Src and Dst\n" << " Src:" << *Src << "\n Dst:" << *Dst << '\n'); Index: llvm/lib/Transforms/Scalar/LoopVersioningLICM.cpp =================================================================== --- llvm/lib/Transforms/Scalar/LoopVersioningLICM.cpp +++ llvm/lib/Transforms/Scalar/LoopVersioningLICM.cpp @@ -92,7 +92,7 @@ #include "llvm/Transforms/Utils/ValueMapper.h" #define DEBUG_TYPE "loop-versioning-licm" -static const char* LICMVersioningMetaData = +static const char LICMVersioningMetaData[] = "llvm.loop.licm_versioning.disable"; using namespace llvm; @@ -122,7 +122,7 @@ } /// \brief Set input string into loop metadata by keeping other values intact. -void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *MDString, +void llvm::addStringMetadataToLoop(Loop *TheLoop, StringRef MDString, unsigned V) { SmallVector MDs(1); // If the loop already has metadata, retain it. Index: llvm/lib/Transforms/Scalar/PlaceSafepoints.cpp =================================================================== --- llvm/lib/Transforms/Scalar/PlaceSafepoints.cpp +++ llvm/lib/Transforms/Scalar/PlaceSafepoints.cpp @@ -428,7 +428,7 @@ return Cursor; } -static const char *const GCSafepointPollName = "gc.safepoint_poll"; +static const char GCSafepointPollName[] = "gc.safepoint_poll"; static bool isGCSafepointPoll(Function &F) { return F.getName().equals(GCSafepointPollName); Index: llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp =================================================================== --- llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp +++ llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp @@ -1296,7 +1296,7 @@ } static StringRef getDeoptLowering(CallSite CS) { - const char *DeoptLowering = "deopt-lowering"; + const char DeoptLowering[] = "deopt-lowering"; if (CS.hasFnAttr(DeoptLowering)) { // FIXME: CallSite has a *really* confusing interface around attributes // with values. Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp =================================================================== --- llvm/lib/Transforms/Utils/ModuleUtils.cpp +++ llvm/lib/Transforms/Utils/ModuleUtils.cpp @@ -20,7 +20,7 @@ using namespace llvm; -static void appendToGlobalArray(const char *Array, Module &M, Function *F, +static void appendToGlobalArray(StringRef Array, Module &M, Function *F, int Priority, Constant *Data) { IRBuilder<> IRB(M.getContext()); FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false); Index: llvm/lib/Transforms/Vectorize/LoopVectorize.cpp =================================================================== --- llvm/lib/Transforms/Vectorize/LoopVectorize.cpp +++ llvm/lib/Transforms/Vectorize/LoopVectorize.cpp @@ -1195,11 +1195,11 @@ /// Hint - associates name and validation with the hint value. struct Hint { - const char *Name; + StringRef Name; unsigned Value; // This may have to change for non-numeric values. HintKind Kind; - Hint(const char *Name, unsigned Value, HintKind Kind) + Hint(StringRef Name, unsigned Value, HintKind Kind) : Name(Name), Value(Value), Kind(Kind) {} bool validate(unsigned Val) { @@ -1455,7 +1455,7 @@ // Now, add the missing hints. for (auto H : HintTypes) - MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value)); + MDs.push_back(createHintMetadata((Prefix() + H.Name).str(), H.Value)); // Replace current metadata node with new one. LLVMContext &Context = TheLoop->getHeader()->getContext(); @@ -7113,7 +7113,7 @@ if (VF.Width == 1) { DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n"); - VecDiagMsg = std::make_pair( + VecDiagMsg = std::make_pair( "VectorizationNotBeneficial", "the cost-model indicates that vectorization is not beneficial"); VectorizeLoop = false; @@ -7122,7 +7122,7 @@ if (IC == 1 && UserIC <= 1) { // Tell the user interleaving is not beneficial. DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n"); - IntDiagMsg = std::make_pair( + IntDiagMsg = std::make_pair( "InterleavingNotBeneficial", "the cost-model indicates that interleaving is not beneficial"); InterleaveLoop = false; @@ -7135,7 +7135,7 @@ // Tell the user interleaving is beneficial, but it explicitly disabled. DEBUG(dbgs() << "LV: Interleaving is beneficial but is explicitly disabled."); - IntDiagMsg = std::make_pair( + IntDiagMsg = std::make_pair( "InterleavingBeneficialButDisabled", "the cost-model indicates that interleaving is beneficial " "but is explicitly disabled or interleave count is set to 1"); Index: llvm/tools/bugpoint/CrashDebugger.cpp =================================================================== --- llvm/tools/bugpoint/CrashDebugger.cpp +++ llvm/tools/bugpoint/CrashDebugger.cpp @@ -208,7 +208,7 @@ }; } -static void RemoveFunctionReferences(Module *M, const char *Name) { +static void RemoveFunctionReferences(Module *M, StringRef Name) { auto *UsedVar = M->getGlobalVariable(Name, true); if (!UsedVar || !UsedVar->hasInitializer()) return; Index: llvm/tools/bugpoint/ExtractFunction.cpp =================================================================== --- llvm/tools/bugpoint/ExtractFunction.cpp +++ llvm/tools/bugpoint/ExtractFunction.cpp @@ -246,7 +246,7 @@ /// M1 has all of the global variables. If M2 contains any functions that are /// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and /// prune appropriate entries out of M1s list. -static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2, +static void SplitStaticCtorDtor(StringRef GlobalName, Module *M1, Module *M2, ValueToValueMapTy &VMap) { GlobalVariable *GV = M1->getNamedGlobal(GlobalName); if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() || !GV->use_empty()) @@ -385,7 +385,7 @@ } sys::RemoveFileOnSignal(Filename); - tool_output_file BlocksToNotExtractFile(Filename.c_str(), FD); + tool_output_file BlocksToNotExtractFile(Filename, FD); for (std::vector::const_iterator I = BBs.begin(), E = BBs.end(); I != E; ++I) { BasicBlock *BB = *I; Index: llvm/tools/bugpoint/bugpoint.cpp =================================================================== --- llvm/tools/bugpoint/bugpoint.cpp +++ llvm/tools/bugpoint/bugpoint.cpp @@ -116,7 +116,7 @@ int main(int argc, char **argv) { #ifndef DEBUG_BUGPOINT - llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); + llvm::sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); llvm::PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. #endif Index: llvm/tools/dsymutil/DwarfLinker.cpp =================================================================== --- llvm/tools/dsymutil/DwarfLinker.cpp +++ llvm/tools/dsymutil/DwarfLinker.cpp @@ -292,12 +292,12 @@ /// \brief Add a name accelerator entry for \p Die with \p Name /// which is stored in the string table at \p Offset. - void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset, + void addNameAccelerator(const DIE *Die, StringRef Name, uint32_t Offset, bool SkipPubnamesSection = false); /// \brief Add a type accelerator entry for \p Die with \p Name /// which is stored in the string table at \p Offset. - void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset); + void addTypeAccelerator(const DIE *Die, StringRef Name, uint32_t Offset); struct AccelInfo { StringRef Name; ///< Name of the entry. @@ -448,14 +448,14 @@ /// \brief Add a name accelerator entry for \p Die with \p Name /// which is stored in the string table at \p Offset. -void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name, +void CompileUnit::addNameAccelerator(const DIE *Die, StringRef Name, uint32_t Offset, bool SkipPubSection) { Pubnames.emplace_back(Name, Die, Offset, SkipPubSection); } /// \brief Add a type accelerator entry for \p Die with \p Name /// which is stored in the string table at \p Offset. -void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name, +void CompileUnit::addTypeAccelerator(const DIE *Die, StringRef Name, uint32_t Offset) { Pubtypes.emplace_back(Name, Die, Offset, false); } @@ -1590,7 +1590,7 @@ StringRef FileRef; if (Name) - NameRef = StringPool.internString(Name); + NameRef = StringPool.internString(StringRef(Name)); else if (Tag == dwarf::DW_TAG_namespace) // FIXME: For dsymutil-classic compatibility. I think uniquing // within anonymous namespaces is wrong. There is no ODR guarantee @@ -1598,7 +1598,7 @@ NameRef = StringPool.internString("(anonymous namespace)"); if (ShortName && ShortName != Name) - ShortNameRef = StringPool.internString(ShortName); + ShortNameRef = StringPool.internString(StringRef(ShortName)); else ShortNameRef = NameRef; @@ -1723,10 +1723,10 @@ if (!Info.MangledName && (Info.MangledName = Die.getName(&U, DINameKind::LinkageName))) Info.MangledNameOffset = - Linker.StringPool.getStringOffset(Info.MangledName); + Linker.StringPool.getStringOffset(StringRef(Info.MangledName)); if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName))) - Info.NameOffset = Linker.StringPool.getStringOffset(Info.Name); + Info.NameOffset = Linker.StringPool.getStringOffset(StringRef(Info.Name)); return Info.Name || Info.MangledName; } @@ -2358,7 +2358,7 @@ const DWARFUnit &U) { // Switch everything to out of line strings. const char *String = *Val.getAsCString(&U); - unsigned Offset = Linker.StringPool.getStringOffset(String); + unsigned Offset = Linker.StringPool.getStringOffset(StringRef(String)); Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp, DIEInteger(Offset)); return 4; @@ -2820,15 +2820,16 @@ Tag != dwarf::DW_TAG_compile_unit && getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) { if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name) - Unit.addNameAccelerator(Die, AttrInfo.MangledName, + Unit.addNameAccelerator(Die, StringRef(AttrInfo.MangledName), AttrInfo.MangledNameOffset, Tag == dwarf::DW_TAG_inlined_subroutine); if (AttrInfo.Name) - Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset, + Unit.addNameAccelerator(Die, StringRef(AttrInfo.Name), + AttrInfo.NameOffset, Tag == dwarf::DW_TAG_inlined_subroutine); } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration && getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) { - Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset); + Unit.addTypeAccelerator(Die, StringRef(AttrInfo.Name), AttrInfo.NameOffset); } // Determine whether there are any children that we want to keep. Index: llvm/tools/dsymutil/MachODebugMapParser.cpp =================================================================== --- llvm/tools/dsymutil/MachODebugMapParser.cpp +++ llvm/tools/dsymutil/MachODebugMapParser.cpp @@ -59,7 +59,7 @@ DebugMapObject *CurrentDebugMapObject; /// Holds function info while function scope processing. - const char *CurrentFunctionName; + StringRef CurrentFunctionName; uint64_t CurrentFunctionAddress; std::unique_ptr parseOneBinary(const MachOObjectFile &MainBinary, @@ -186,12 +186,12 @@ {MachO::N_ECOMM, "N_ECOMM"}, {MachO::N_ECOML, "N_ECOML"}, {MachO::N_LENG, "N_LENG"}, {0, nullptr}}; -static const char *getDarwinStabString(uint8_t NType) { +static StringRef getDarwinStabString(uint8_t NType) { for (unsigned i = 0; DarwinStabNames[i].Name; i++) { if (DarwinStabNames[i].NType == NType) - return DarwinStabNames[i].Name; + return StringRef(DarwinStabNames[i].Name); } - return nullptr; + return StringRef(); } void MachODebugMapParser::dumpSymTabHeader(raw_ostream &OS, StringRef Arch) { @@ -340,7 +340,7 @@ if (!(Type & MachO::N_STAB)) return; - const char *Name = &MainBinaryStrings.data()[StringIndex]; + StringRef Name(&MainBinaryStrings.data()[StringIndex]); // An N_OSO entry represents the start of a new object file description. if (Type == MachO::N_OSO) { @@ -366,7 +366,7 @@ case MachO::N_FUN: // Functions are scopes in STABS. They have an end marker that // contains the function size. - if (Name[0] == '\0') { + if (Name.data()[0] == '\0') { Size = Value; Value = CurrentFunctionAddress; Name = CurrentFunctionName; Index: llvm/tools/dsymutil/dsymutil.cpp =================================================================== --- llvm/tools/dsymutil/dsymutil.cpp +++ llvm/tools/dsymutil/dsymutil.cpp @@ -237,7 +237,7 @@ } int main(int argc, char **argv) { - llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); + llvm::sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0])); llvm::PrettyStackTraceProgram StackPrinter(argc, argv); llvm::llvm_shutdown_obj Shutdown; LinkOptions Options; Index: llvm/tools/llc/llc.cpp =================================================================== --- llvm/tools/llc/llc.cpp +++ llvm/tools/llc/llc.cpp @@ -240,7 +240,7 @@ // main - Entry point for the llc compiler. // int main(int argc, char **argv) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); // Enable debug stream buffering. @@ -345,7 +345,7 @@ } else M = parseIRFile(InputFilename, Err, Context); if (!M) { - Err.print(argv[0], errs()); + Err.print(StringRef(argv[0]), errs()); return 1; } Index: llvm/tools/lli/lli.cpp =================================================================== --- llvm/tools/lli/lli.cpp +++ llvm/tools/lli/lli.cpp @@ -361,13 +361,14 @@ // main Driver function // int main(int argc, char **argv, char * const *envp) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + StringRef ProgName(argv[0]); + sys::PrintStackTraceOnErrorSignal(ProgName); PrettyStackTraceProgram X(argc, argv); atexit(llvm_shutdown); // Call llvm_shutdown() on exit. if (argc > 1) - ExitOnErr.setBanner(std::string(argv[0]) + ": "); + ExitOnErr.setBanner((ProgName + ": ").str()); // If we have a native target, initialize it to ensure it is linked in and // usable by the JIT. @@ -389,7 +390,7 @@ std::unique_ptr Owner = parseIRFile(InputFile, Err, Context); Module *Mod = Owner.get(); if (!Mod) { - Err.print(argv[0], errs()); + Err.print(ProgName, errs()); return 1; } Index: llvm/tools/llvm-ar/llvm-ar.cpp =================================================================== --- llvm/tools/llvm-ar/llvm-ar.cpp +++ llvm/tools/llvm-ar/llvm-ar.cpp @@ -833,9 +833,9 @@ } int main(int argc, char **argv) { - ToolName = argv[0]; + ToolName = StringRef(argv[0]); // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(ToolName); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. Index: llvm/tools/llvm-as/llvm-as.cpp =================================================================== --- llvm/tools/llvm-as/llvm-as.cpp +++ llvm/tools/llvm-as/llvm-as.cpp @@ -89,7 +89,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); LLVMContext Context; llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. @@ -99,7 +99,7 @@ SMDiagnostic Err; std::unique_ptr M = parseAssemblyFile(InputFilename, Err, Context); if (!M.get()) { - Err.print(argv[0], errs()); + Err.print(StringRef(argv[0]), errs()); return 1; } Index: llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp =================================================================== --- llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp +++ llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp @@ -915,7 +915,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm-bcanalyzer file analyzer\n"); Index: llvm/tools/llvm-config/llvm-config.cpp =================================================================== --- llvm/tools/llvm-config/llvm-config.cpp +++ llvm/tools/llvm-config/llvm-config.cpp @@ -118,7 +118,7 @@ // Add to the required library list. if (AC->Library) { if (Missing && GetComponentLibraryPath) { - std::string path = (*GetComponentLibraryPath)(AC->Library); + std::string path = (*GetComponentLibraryPath)(StringRef(AC->Library)); if (DirSep == "\\") { std::replace(path.begin(), path.end(), '/', '\\'); } @@ -149,7 +149,7 @@ StringMap ComponentMap; for (unsigned i = 0; i != array_lengthof(AvailableComponents); ++i) { AvailableComponent *AC = &AvailableComponents[i]; - ComponentMap[AC->Name] = AC; + ComponentMap[StringRef(AC->Name)] = AC; } // Visit the components. @@ -452,7 +452,7 @@ raw_ostream &OS = outs(); for (int i = 1; i != argc; ++i) { - StringRef Arg = argv[i]; + StringRef Arg(argv[i]); if (Arg.startswith("-")) { HasAnyOption = true; @@ -495,8 +495,8 @@ Components.push_back(AvailableComponents[j].Name); if (AvailableComponents[j].Library && !IsInDevelopmentTree) { - std::string path( - GetComponentLibraryPath(AvailableComponents[j].Library, false)); + std::string path(GetComponentLibraryPath( + StringRef(AvailableComponents[j].Library), false)); if (DirSep == "\\") { std::replace(path.begin(), path.end(), '/', '\\'); } Index: llvm/tools/llvm-cov/llvm-cov.cpp =================================================================== --- llvm/tools/llvm-cov/llvm-cov.cpp +++ llvm/tools/llvm-cov/llvm-cov.cpp @@ -60,18 +60,18 @@ int main(int argc, const char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. // If argv[0] is or ends with 'gcov', always be gcov compatible - if (sys::path::stem(argv[0]).endswith_lower("gcov")) + if (sys::path::stem(StringRef(argv[0])).endswith_lower("gcov")) return gcovMain(argc, argv); // Check if we are invoking a specific tool command. if (argc > 1) { typedef int (*MainFunction)(int, const char *[]); - MainFunction Func = StringSwitch(argv[1]) + MainFunction Func = StringSwitch(StringRef(argv[1])) .Case("convert-for-testing", convertForTestingMain) .Case("export", exportMain) .Case("gcov", gcovMain) Index: llvm/tools/llvm-cxxdump/llvm-cxxdump.cpp =================================================================== --- llvm/tools/llvm-cxxdump/llvm-cxxdump.cpp +++ llvm/tools/llvm-cxxdump/llvm-cxxdump.cpp @@ -533,7 +533,7 @@ } int main(int argc, const char *argv[]) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; Index: llvm/tools/llvm-dis/llvm-dis.cpp =================================================================== --- llvm/tools/llvm-dis/llvm-dis.cpp +++ llvm/tools/llvm-dis/llvm-dis.cpp @@ -171,7 +171,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); LLVMContext Context; Index: llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp =================================================================== --- llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp +++ llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp @@ -147,7 +147,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. Index: llvm/tools/llvm-dwp/llvm-dwp.cpp =================================================================== --- llvm/tools/llvm-dwp/llvm-dwp.cpp +++ llvm/tools/llvm-dwp/llvm-dwp.cpp @@ -459,7 +459,8 @@ std::string("Duplicate DWO ID (") + utohexstr(PrevE.first) + ") in " + buildDWODescription(PrevE.second.Name, PrevE.second.DWPName, PrevE.second.DWOName) + - " and " + buildDWODescription(ID.Name, DWPName, ID.DWOName)); + " and " + + buildDWODescription(StringRef(ID.Name), DWPName, StringRef(ID.DWOName))); } static Error write(MCStreamer &Out, ArrayRef Inputs) { Index: llvm/tools/llvm-extract/llvm-extract.cpp =================================================================== --- llvm/tools/llvm-extract/llvm-extract.cpp +++ llvm/tools/llvm-extract/llvm-extract.cpp @@ -102,7 +102,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); LLVMContext Context; @@ -114,7 +114,7 @@ std::unique_ptr M = getLazyIRFileModule(InputFilename, Err, Context); if (!M.get()) { - Err.print(argv[0], errs()); + Err.print(StringRef(argv[0]), errs()); return 1; } Index: llvm/tools/llvm-jitlistener/llvm-jitlistener.cpp =================================================================== --- llvm/tools/llvm-jitlistener/llvm-jitlistener.cpp +++ llvm/tools/llvm-jitlistener/llvm-jitlistener.cpp @@ -179,7 +179,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. Index: llvm/tools/llvm-link/llvm-link.cpp =================================================================== --- llvm/tools/llvm-link/llvm-link.cpp +++ llvm/tools/llvm-link/llvm-link.cpp @@ -124,7 +124,7 @@ Result = getLazyIRFileModule(FN, Err, Context, !MaterializeMetadata); if (!Result) { - Err.print(argv0, errs()); + Err.print(StringRef(argv0), errs()); return nullptr; } @@ -345,7 +345,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); LLVMContext Context; Index: llvm/tools/llvm-lto/llvm-lto.cpp =================================================================== --- llvm/tools/llvm-lto/llvm-lto.cpp +++ llvm/tools/llvm-lto/llvm-lto.cpp @@ -742,7 +742,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. @@ -823,7 +823,7 @@ for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) { CurrentActivity = "loading file '" + InputFilenames[i] + "'"; ErrorOr> ModuleOrErr = - LTOModule::createFromFile(Context, InputFilenames[i].c_str(), Options); + LTOModule::createFromFile(Context, InputFilenames[i], Options); std::unique_ptr &Module = *ModuleOrErr; CurrentActivity = ""; @@ -851,14 +851,14 @@ // Add all the exported symbols to the table of symbols to preserve. for (unsigned i = 0; i < ExportedSymbols.size(); ++i) - CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str()); + CodeGen.addMustPreserveSymbol(ExportedSymbols[i]); // Add all the dso symbols to the table of symbols to expose. for (unsigned i = 0; i < KeptDSOSyms.size(); ++i) - CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str()); + CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]); // Set cpu and attrs strings for the default target/subtarget. - CodeGen.setCpu(MCPU.c_str()); + CodeGen.setCpu(MCPU); CodeGen.setOptLevel(OptLevel - '0'); @@ -870,7 +870,7 @@ } if (!attrs.empty()) - CodeGen.setAttr(attrs.c_str()); + CodeGen.setAttr(attrs); if (FileType.getNumOccurrences()) CodeGen.setFileType(FileType); @@ -887,7 +887,7 @@ ModuleFilename += ".merged.bc"; std::string ErrMsg; - if (!CodeGen.writeMergedModules(ModuleFilename.c_str())) + if (!CodeGen.writeMergedModules(ModuleFilename)) error("writing merged module failed."); } Index: llvm/tools/llvm-mc/llvm-mc.cpp =================================================================== --- llvm/tools/llvm-mc/llvm-mc.cpp +++ llvm/tools/llvm-mc/llvm-mc.cpp @@ -441,7 +441,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. Index: llvm/tools/llvm-mcmarkup/llvm-mcmarkup.cpp =================================================================== --- llvm/tools/llvm-mcmarkup/llvm-mcmarkup.cpp +++ llvm/tools/llvm-mcmarkup/llvm-mcmarkup.cpp @@ -207,14 +207,14 @@ } int main(int argc, char **argv) { + ToolName = StringRef(argv[0]); // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(ToolName); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm MC markup parser\n"); - ToolName = argv[0]; // If no input files specified, read from stdin. if (InputFilenames.size() == 0) Index: llvm/tools/llvm-nm/llvm-nm.cpp =================================================================== --- llvm/tools/llvm-nm/llvm-nm.cpp +++ llvm/tools/llvm-nm/llvm-nm.cpp @@ -1037,8 +1037,9 @@ OS.flush(); const char *P = NameBuffer.c_str(); for (unsigned I = 0; I < SymbolList.size(); ++I) { - SymbolList[I].Name = P; - P += strlen(P) + 1; + StringRef PStr(P); + SymbolList[I].Name = PStr; + P += PStr.size() + 1; } CurrentFilename = Obj.getFileName(); @@ -1367,7 +1368,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. Index: llvm/tools/llvm-objdump/MachODump.cpp =================================================================== --- llvm/tools/llvm-objdump/MachODump.cpp +++ llvm/tools/llvm-objdump/MachODump.cpp @@ -3333,8 +3333,8 @@ return n_value; } -static const SectionRef get_section(MachOObjectFile *O, const char *segname, - const char *sectname) { +static const SectionRef get_section(MachOObjectFile *O, StringRef segname, + StringRef sectname) { for (const SectionRef &Section : O->sections()) { StringRef SectName; Section.getName(SectName); @@ -7096,7 +7096,7 @@ // First populate the initial raw offsets, encodings and so on from the entry. for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) { - CompactUnwindEntry Entry(Contents.data(), Offset, Is64); + CompactUnwindEntry Entry(Contents, Offset, Is64); CompactUnwinds.push_back(Entry); } Index: llvm/tools/llvm-objdump/llvm-objdump.cpp =================================================================== --- llvm/tools/llvm-objdump/llvm-objdump.cpp +++ llvm/tools/llvm-objdump/llvm-objdump.cpp @@ -1556,8 +1556,7 @@ } void llvm::PrintRelocations(const ObjectFile *Obj) { - StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : - "%08" PRIx64; + StringRef Fmt(Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64); // Regular objdump doesn't print relocations in non-relocatable object // files. if (!Obj->isRelocatableObject()) @@ -1852,7 +1851,7 @@ } static void printFaultMaps(const ObjectFile *Obj) { - const char *FaultMapSectionName = nullptr; + StringRef FaultMapSectionName; if (isa(Obj)) { FaultMapSectionName = ".llvm_faultmaps"; @@ -2014,7 +2013,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. @@ -2029,7 +2028,7 @@ cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); TripleName = Triple::normalize(TripleName); - ToolName = argv[0]; + ToolName = StringRef(argv[0]); // Defaults to a.out if no filenames specified. if (InputFilenames.size() == 0) Index: llvm/tools/llvm-opt-report/OptReport.cpp =================================================================== --- llvm/tools/llvm-opt-report/OptReport.cpp +++ llvm/tools/llvm-opt-report/OptReport.cpp @@ -498,7 +498,7 @@ } int main(int argc, const char **argv) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0])); cl::HideUnrelatedOptions(OptReportCategory); cl::ParseCommandLineOptions( Index: llvm/tools/llvm-pdbdump/llvm-pdbdump.cpp =================================================================== --- llvm/tools/llvm-pdbdump/llvm-pdbdump.cpp +++ llvm/tools/llvm-pdbdump/llvm-pdbdump.cpp @@ -524,7 +524,7 @@ int main(int argc_, const char *argv_[]) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv_[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv_[0])); PrettyStackTraceProgram X(argc_, argv_); ExitOnErr.setBanner("llvm-pdbdump: "); Index: llvm/tools/llvm-profdata/llvm-profdata.cpp =================================================================== --- llvm/tools/llvm-profdata/llvm-profdata.cpp +++ llvm/tools/llvm-profdata/llvm-profdata.cpp @@ -183,7 +183,7 @@ exitWithError("Unknown format is specified."); std::error_code EC; - raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None); + raw_fd_ostream Output(OutputFilename, EC, sys::fs::F_None); if (EC) exitWithErrorCode(EC, OutputFilename); @@ -423,7 +423,7 @@ if (WeightedInputs.empty()) exitWithError("No input files specified. See " + - sys::path::filename(argv[0]) + " -help"); + sys::path::filename(StringRef(argv[0])) + " -help"); if (DumpInputFileList) { for (auto &WF : WeightedInputs) @@ -629,7 +629,7 @@ OutputFilename = "-"; std::error_code EC; - raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text); + raw_fd_ostream OS(OutputFilename, EC, sys::fs::F_Text); if (EC) exitWithErrorCode(EC, OutputFilename); @@ -649,11 +649,11 @@ int main(int argc, const char *argv[]) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. - StringRef ProgName(sys::path::filename(argv[0])); + StringRef ProgName(sys::path::filename(StringRef(argv[0]))); if (argc > 1) { int (*func)(int, const char *[]) = nullptr; Index: llvm/tools/llvm-readobj/ARMAttributeParser.cpp =================================================================== --- llvm/tools/llvm-readobj/ARMAttributeParser.cpp +++ llvm/tools/llvm-readobj/ARMAttributeParser.cpp @@ -119,15 +119,14 @@ void ARMAttributeParser::CPU_arch(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Pre-v4", "ARM v4", "ARM v4T", "ARM v5T", "ARM v5TE", "ARM v5TEJ", "ARM v6", - "ARM v6KZ", "ARM v6T2", "ARM v6K", "ARM v7", "ARM v6-M", "ARM v6S-M", - "ARM v7E-M", "ARM v8" - }; + static StringRef const Strings[] = { + "Pre-v4", "ARM v4", "ARM v4T", "ARM v5T", "ARM v5TE", + "ARM v5TEJ", "ARM v6", "ARM v6KZ", "ARM v6T2", "ARM v6K", + "ARM v7", "ARM v6-M", "ARM v6S-M", "ARM v7E-M", "ARM v8"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } @@ -150,190 +149,184 @@ void ARMAttributeParser::ARM_ISA_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "Not Permitted", "Permitted" }; + static StringRef const Strings[] = {"Not Permitted", "Permitted"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::THUMB_ISA_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "Not Permitted", "Thumb-1", "Thumb-2" }; + static StringRef const Strings[] = {"Not Permitted", "Thumb-1", "Thumb-2"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::FP_arch(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Not Permitted", "VFPv1", "VFPv2", "VFPv3", "VFPv3-D16", "VFPv4", - "VFPv4-D16", "ARMv8-a FP", "ARMv8-a FP-D16" - }; + static StringRef const Strings[] = { + "Not Permitted", "VFPv1", "VFPv2", "VFPv3", "VFPv3-D16", + "VFPv4", "VFPv4-D16", "ARMv8-a FP", "ARMv8-a FP-D16"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::WMMX_arch(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "Not Permitted", "WMMXv1", "WMMXv2" }; + static StringRef const Strings[] = {"Not Permitted", "WMMXv1", "WMMXv2"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::Advanced_SIMD_arch(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Not Permitted", "NEONv1", "NEONv2+FMA", "ARMv8-a NEON", "ARMv8.1-a NEON" - }; + static StringRef const Strings[] = {"Not Permitted", "NEONv1", "NEONv2+FMA", + "ARMv8-a NEON", "ARMv8.1-a NEON"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::PCS_config(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "None", "Bare Platform", "Linux Application", "Linux DSO", "Palm OS 2004", - "Reserved (Palm OS)", "Symbian OS 2004", "Reserved (Symbian OS)" - }; - - uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + static StringRef const Strings[] = {"None", + "Bare Platform", + "Linux Application", + "Linux DSO", + "Palm OS 2004", + "Reserved (Palm OS)", + "Symbian OS 2004", + "Reserved (Symbian OS)"}; + + uint64_t Value = ParseInteger(Data, Offset); + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_PCS_R9_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "v6", "Static Base", "TLS", "Unused" }; + static StringRef const Strings[] = {"v6", "Static Base", "TLS", "Unused"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_PCS_RW_data(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Absolute", "PC-relative", "SB-relative", "Not Permitted" - }; + static StringRef const Strings[] = {"Absolute", "PC-relative", "SB-relative", + "Not Permitted"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_PCS_RO_data(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Absolute", "PC-relative", "Not Permitted" - }; + static StringRef const Strings[] = {"Absolute", "PC-relative", + "Not Permitted"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_PCS_GOT_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Not Permitted", "Direct", "GOT-Indirect" - }; + static StringRef const Strings[] = {"Not Permitted", "Direct", + "GOT-Indirect"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_PCS_wchar_t(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Not Permitted", "Unknown", "2-byte", "Unknown", "4-byte" - }; + static StringRef const Strings[] = {"Not Permitted", "Unknown", "2-byte", + "Unknown", "4-byte"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_rounding(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "IEEE-754", "Runtime" }; + static StringRef const Strings[] = {"IEEE-754", "Runtime"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_denormal(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Unsupported", "IEEE-754", "Sign Only" - }; + static StringRef const Strings[] = {"Unsupported", "IEEE-754", "Sign Only"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_exceptions(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "Not Permitted", "IEEE-754" }; + static StringRef const Strings[] = {"Not Permitted", "IEEE-754"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_user_exceptions(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "Not Permitted", "IEEE-754" }; + static StringRef const Strings[] = {"Not Permitted", "IEEE-754"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_number_model(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Not Permitted", "Finite Only", "RTABI", "IEEE-754" - }; + static StringRef const Strings[] = {"Not Permitted", "Finite Only", "RTABI", + "IEEE-754"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_align_needed(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Not Permitted", "8-byte alignment", "4-byte alignment", "Reserved" - }; + static StringRef const Strings[] = {"Not Permitted", "8-byte alignment", + "4-byte alignment", "Reserved"}; uint64_t Value = ParseInteger(Data, Offset); @@ -351,10 +344,9 @@ void ARMAttributeParser::ABI_align_preserved(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Not Required", "8-byte data alignment", "8-byte data and code alignment", - "Reserved" - }; + static StringRef const Strings[] = {"Not Required", "8-byte data alignment", + "8-byte data and code alignment", + "Reserved"}; uint64_t Value = ParseInteger(Data, Offset); @@ -372,75 +364,71 @@ void ARMAttributeParser::ABI_enum_size(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Not Permitted", "Packed", "Int32", "External Int32" - }; + static StringRef const Strings[] = {"Not Permitted", "Packed", "Int32", + "External Int32"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_HardFP_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Tag_FP_arch", "Single-Precision", "Reserved", "Tag_FP_arch (deprecated)" - }; + static StringRef const Strings[] = {"Tag_FP_arch", "Single-Precision", + "Reserved", "Tag_FP_arch (deprecated)"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_VFP_args(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "AAPCS", "AAPCS VFP", "Custom", "Not Permitted" - }; + static StringRef const Strings[] = {"AAPCS", "AAPCS VFP", "Custom", + "Not Permitted"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_WMMX_args(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "AAPCS", "iWMMX", "Custom" }; + static StringRef const Strings[] = {"AAPCS", "iWMMX", "Custom"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_optimization_goals(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "None", "Speed", "Aggressive Speed", "Size", "Aggressive Size", "Debugging", - "Best Debugging" - }; + static StringRef const Strings[] = { + "None", "Speed", "Aggressive Speed", + "Size", "Aggressive Size", "Debugging", + "Best Debugging"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_optimization_goals(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "None", "Speed", "Aggressive Speed", "Size", "Aggressive Size", "Accuracy", - "Best Accuracy" - }; + static StringRef const Strings[] = { + "None", "Speed", "Aggressive Speed", "Size", "Aggressive Size", + "Accuracy", "Best Accuracy"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } @@ -468,86 +456,84 @@ void ARMAttributeParser::CPU_unaligned_access(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "Not Permitted", "v6-style" }; + static StringRef const Strings[] = {"Not Permitted", "v6-style"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::FP_HP_extension(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "If Available", "Permitted" }; + static StringRef const Strings[] = {"If Available", "Permitted"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::ABI_FP_16bit_format(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "Not Permitted", "IEEE-754", "VFPv3" }; + static StringRef const Strings[] = {"Not Permitted", "IEEE-754", "VFPv3"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::MPextension_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "Not Permitted", "Permitted" }; + static StringRef const Strings[] = {"Not Permitted", "Permitted"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::DIV_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "If Available", "Not Permitted", "Permitted" - }; + static StringRef const Strings[] = {"If Available", "Not Permitted", + "Permitted"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::DSP_extension(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "Not Permitted", "Permitted" }; + static StringRef const Strings[] = {"Not Permitted", "Permitted"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::T2EE_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { "Not Permitted", "Permitted" }; + static StringRef const Strings[] = {"Not Permitted", "Permitted"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } void ARMAttributeParser::Virtualization_use(AttrType Tag, const uint8_t *Data, uint32_t &Offset) { - static const char *const Strings[] = { - "Not Permitted", "TrustZone", "Virtualization Extensions", - "TrustZone + Virtualization Extensions" - }; + static StringRef const Strings[] = {"Not Permitted", "TrustZone", + "Virtualization Extensions", + "TrustZone + Virtualization Extensions"}; uint64_t Value = ParseInteger(Data, Offset); - StringRef ValueDesc = - (Value < array_lengthof(Strings)) ? Strings[Value] : nullptr; + StringRef ValueDesc((Value < array_lengthof(Strings)) ? Strings[Value] + : StringRef()); PrintAttribute(Tag, Value, ValueDesc); } Index: llvm/tools/llvm-readobj/ELFDumper.cpp =================================================================== --- llvm/tools/llvm-readobj/ELFDumper.cpp +++ llvm/tools/llvm-readobj/ELFDumper.cpp @@ -978,7 +978,7 @@ { "AMDGPU_HSA_METADATA", ELF::STT_AMDGPU_HSA_METADATA } }; -static const char *getElfSectionType(unsigned Arch, unsigned Type) { +static StringRef getElfSectionType(unsigned Arch, unsigned Type) { switch (Arch) { case ELF::EM_ARM: switch (Type) { @@ -1028,7 +1028,7 @@ } } -static const char *getGroupType(uint32_t Flag) { +static StringRef getGroupType(uint32_t Flag) { if (Flag & ELF::GRP_COMDAT) return "COMDAT"; else @@ -1114,7 +1114,7 @@ return Str; } -static const char *getElfSegmentType(unsigned Arch, unsigned Type) { +static StringRef getElfSegmentType(unsigned Arch, unsigned Type) { // Check potentially overlapped processor-specific // program header type. switch (Arch) { @@ -1276,7 +1276,7 @@ LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MIPS16) }; -static const char *getElfMipsOptionsOdkType(unsigned Odk) { +static StringRef getElfMipsOptionsOdkType(unsigned Odk) { switch (Odk) { LLVM_READOBJ_ENUM_CASE(ELF, ODK_NULL); LLVM_READOBJ_ENUM_CASE(ELF, ODK_REGINFO); @@ -1490,7 +1490,7 @@ #define LLVM_READOBJ_TYPE_CASE(name) \ case DT_##name: return #name -static const char *getTypeString(uint64_t Type) { +static StringRef getTypeString(uint64_t Type) { switch (Type) { LLVM_READOBJ_TYPE_CASE(BIND_NOW); LLVM_READOBJ_TYPE_CASE(DEBUG); @@ -1778,8 +1778,9 @@ const Elf_Dyn &Entry = *I; uintX_t Tag = Entry.getTag(); ++I; - W.startLine() << " " << format_hex(Tag, Is64 ? 18 : 10, opts::Output != opts::GNU) << " " - << format("%-21s", getTypeString(Tag)); + W.startLine() << " " + << format_hex(Tag, Is64 ? 18 : 10, opts::Output != opts::GNU) + << " " << format("%-21s", getTypeString(Tag).str().c_str()); printValue(Tag, Entry.getVal()); OS << "\n"; } @@ -2991,7 +2992,7 @@ Fields[0].Str = Offset; Fields[1].Str = Info; - Fields[2].Str = RelocName.c_str(); + Fields[2].Str = RelocName; Fields[3].Str = Value; Fields[4].Str = SymbolName; for (auto &Field : Fields) @@ -3183,7 +3184,7 @@ default: return; case ELF::NT_GNU_ABI_TAG: { - static const char *OSNames[] = { + static StringRef OSNames[] = { "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable", "NaCl", }; Index: llvm/tools/llvm-readobj/MachODumper.cpp =================================================================== --- llvm/tools/llvm-readobj/MachODumper.cpp +++ llvm/tools/llvm-readobj/MachODumper.cpp @@ -563,7 +563,7 @@ if (IsScattered) { W.printHex("Value", Obj->getScatteredRelocationValue(RE)); } else { - const char *Kind = IsExtern ? "Symbol" : "Section"; + StringRef Kind(IsExtern ? "Symbol" : "Section"); W.printNumber(Kind, TargetName, Obj->getPlainRelocationSymbolNum(RE)); } } else { Index: llvm/tools/llvm-readobj/llvm-readobj.cpp =================================================================== --- llvm/tools/llvm-readobj/llvm-readobj.cpp +++ llvm/tools/llvm-readobj/llvm-readobj.cpp @@ -523,7 +523,7 @@ } int main(int argc, const char *argv[]) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; Index: llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp =================================================================== --- llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp +++ llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp @@ -728,7 +728,7 @@ } int main(int argc, char **argv) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); ProgramName = argv[0]; Index: llvm/tools/llvm-size/llvm-size.cpp =================================================================== --- llvm/tools/llvm-size/llvm-size.cpp +++ llvm/tools/llvm-size/llvm-size.cpp @@ -857,7 +857,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. Index: llvm/tools/llvm-symbolizer/llvm-symbolizer.cpp =================================================================== --- llvm/tools/llvm-symbolizer/llvm-symbolizer.cpp +++ llvm/tools/llvm-symbolizer/llvm-symbolizer.cpp @@ -139,7 +139,7 @@ int main(int argc, char **argv) { // Print stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. @@ -181,7 +181,7 @@ if (ClPrintAddress) { outs() << "0x"; outs().write_hex(ModuleOffset); - StringRef Delimiter = (ClPrettyPrint == true) ? ": " : "\n"; + StringRef Delimiter(ClPrettyPrint == true ? ": " : "\n"); outs() << Delimiter; } if (IsData) { Index: llvm/tools/lto/lto.cpp =================================================================== --- llvm/tools/lto/lto.cpp +++ llvm/tools/lto/lto.cpp @@ -153,7 +153,7 @@ attrs.append(MAttrs[i]); } - CG->setAttr(attrs.c_str()); + CG->setAttr(StringRef(attrs.c_str())); } if (OptLevel < '0' || OptLevel > '3') @@ -375,7 +375,7 @@ } void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) { - return unwrap(cg)->setCpu(cpu); + return unwrap(cg)->setCpu(StringRef(cpu)); } void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) { @@ -389,7 +389,7 @@ void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char *symbol) { - unwrap(cg)->addMustPreserveSymbol(symbol); + unwrap(cg)->addMustPreserveSymbol(StringRef(symbol)); } static void maybeParseOptions(lto_code_gen_t cg) { @@ -402,7 +402,7 @@ bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) { maybeParseOptions(cg); - return !unwrap(cg)->writeMergedModules(path); + return !unwrap(cg)->writeMergedModules(StringRef(path)); } const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) { @@ -441,7 +441,7 @@ } void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) { - unwrap(cg)->setCodeGenDebugOptions(opt); + unwrap(cg)->setCodeGenDebugOptions(StringRef(opt)); } unsigned int lto_api_version() { return LTO_API_VERSION; } @@ -470,7 +470,7 @@ void thinlto_codegen_add_module(thinlto_code_gen_t cg, const char *Identifier, const char *Data, int Length) { - unwrap(cg)->addModule(Identifier, StringRef(Data, Length)); + unwrap(cg)->addModule(StringRef(Identifier), StringRef(Data, Length)); } void thinlto_codegen_process(thinlto_code_gen_t cg) { unwrap(cg)->run(); } Index: llvm/tools/obj2yaml/obj2yaml.cpp =================================================================== --- llvm/tools/obj2yaml/obj2yaml.cpp +++ llvm/tools/obj2yaml/obj2yaml.cpp @@ -50,7 +50,7 @@ int main(int argc, char *argv[]) { cl::ParseCommandLineOptions(argc, argv); - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. Index: llvm/tools/opt/PassPrinters.cpp =================================================================== --- llvm/tools/opt/PassPrinters.cpp +++ llvm/tools/opt/PassPrinters.cpp @@ -46,7 +46,7 @@ return false; } - StringRef getPassName() const override { return PassName.c_str(); } + StringRef getPassName() const override { return PassName; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequiredID(PassToPrint->getTypeInfo()); @@ -83,7 +83,7 @@ return false; } - StringRef getPassName() const override { return PassName.c_str(); } + StringRef getPassName() const override { return PassName; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequiredID(PassToPrint->getTypeInfo()); @@ -115,7 +115,7 @@ return false; } - StringRef getPassName() const override { return PassName.c_str(); } + StringRef getPassName() const override { return PassName; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequiredID(PassToPrint->getTypeInfo()); @@ -148,7 +148,7 @@ return false; } - StringRef getPassName() const override { return PassName.c_str(); } + StringRef getPassName() const override { return PassName; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequiredID(PassToPrint->getTypeInfo()); @@ -183,7 +183,7 @@ return false; } - StringRef getPassName() const override { return PassName.c_str(); } + StringRef getPassName() const override { return PassName; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequiredID(PassToPrint->getTypeInfo()); @@ -217,7 +217,7 @@ return false; } - StringRef getPassName() const override { return PassName.c_str(); } + StringRef getPassName() const override { return PassName; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequiredID(PassToPrint->getTypeInfo()); Index: llvm/tools/opt/opt.cpp =================================================================== --- llvm/tools/opt/opt.cpp +++ llvm/tools/opt/opt.cpp @@ -352,7 +352,7 @@ // main for opt // int main(int argc, char **argv) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); llvm::PrettyStackTraceProgram X(argc, argv); // Enable debug stream buffering. @@ -430,7 +430,7 @@ std::unique_ptr M = parseIRFile(InputFilename, Err, Context); if (!M) { - Err.print(argv[0], errs()); + Err.print(StringRef(argv[0]), errs()); return 1; } @@ -508,7 +508,7 @@ // The user has asked to use the new pass manager and provided a pipeline // string. Hand off the rest of the functionality to the new code for that // layer. - return runPassPipeline(argv[0], *M, TM.get(), Out.get(), + return runPassPipeline(StringRef(argv[0]), *M, TM.get(), Out.get(), PassPipeline, OK, VK, PreserveAssemblyUseListOrder, PreserveBitcodeUseListOrder, EmitSummaryIndex, EmitModuleHash) Index: llvm/tools/sancov/sancov.cc =================================================================== --- llvm/tools/sancov/sancov.cc +++ llvm/tools/sancov/sancov.cc @@ -113,9 +113,9 @@ "use_default_blacklist", cl::init(true), cl::Hidden, cl::desc("Controls if default blacklist should be used.")); -static const char *const DefaultBlacklistStr = "fun:__sanitizer_.*\n" - "src:/usr/include/.*\n" - "src:.*/libc\\+\\+/.*\n"; +static const char DefaultBlacklistStr[] = "fun:__sanitizer_.*\n" + "src:/usr/include/.*\n" + "src:.*/libc\\+\\+/.*\n"; // --------- FORMAT SPECIFICATION --------- @@ -1158,7 +1158,7 @@ int main(int Argc, char **Argv) { // Print stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(Argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(Argv[0])); PrettyStackTraceProgram X(Argc, Argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. Index: llvm/tools/verify-uselistorder/verify-uselistorder.cpp =================================================================== --- llvm/tools/verify-uselistorder/verify-uselistorder.cpp +++ llvm/tools/verify-uselistorder/verify-uselistorder.cpp @@ -526,7 +526,7 @@ } int main(int argc, char **argv) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); llvm::PrettyStackTraceProgram X(argc, argv); // Enable debug stream buffering. Index: llvm/tools/yaml2obj/yaml2obj.cpp =================================================================== --- llvm/tools/yaml2obj/yaml2obj.cpp +++ llvm/tools/yaml2obj/yaml2obj.cpp @@ -69,7 +69,7 @@ int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. Index: llvm/unittests/ADT/APFloatTest.cpp =================================================================== --- llvm/unittests/ADT/APFloatTest.cpp +++ llvm/unittests/ADT/APFloatTest.cpp @@ -18,7 +18,7 @@ using namespace llvm; -static double convertToDoubleFromString(const char *Str) { +static double convertToDoubleFromString(StringRef Str) { llvm::APFloat F(0.0); F.convertFromString(Str, llvm::APFloat::rmNearestTiesToEven); return F.convertToDouble(); @@ -556,7 +556,7 @@ // Test single precision { - const char *MinNormalStr = "1.17549435082228750797e-38"; + const char MinNormalStr[] = "1.17549435082228750797e-38"; EXPECT_FALSE(APFloat(APFloat::IEEEsingle, MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::IEEEsingle, 0.0).isDenormal()); @@ -568,7 +568,7 @@ // Test double precision { - const char *MinNormalStr = "2.22507385850720138309e-308"; + const char MinNormalStr[] = "2.22507385850720138309e-308"; EXPECT_FALSE(APFloat(APFloat::IEEEdouble, MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::IEEEdouble, 0.0).isDenormal()); @@ -580,7 +580,7 @@ // Test Intel double-ext { - const char *MinNormalStr = "3.36210314311209350626e-4932"; + const char MinNormalStr[] = "3.36210314311209350626e-4932"; EXPECT_FALSE(APFloat(APFloat::x87DoubleExtended, MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::x87DoubleExtended, 0.0).isDenormal()); @@ -592,7 +592,7 @@ // Test quadruple precision { - const char *MinNormalStr = "3.36210314311209350626267781732175260e-4932"; + const char MinNormalStr[] = "3.36210314311209350626267781732175260e-4932"; EXPECT_FALSE(APFloat(APFloat::IEEEquad, MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::IEEEquad, 0.0).isDenormal()); @@ -1418,7 +1418,7 @@ for (unsigned i = 0; i < NumGetZeroTests; ++i) { APFloat test = APFloat::getZero(*GetZeroTest[i].semantics, GetZeroTest[i].sign); - const char *pattern = GetZeroTest[i].sign? "-0x0p+0" : "0x0p+0"; + StringRef pattern(GetZeroTest[i].sign ? "-0x0p+0" : "0x0p+0"); APFloat expected = APFloat(*GetZeroTest[i].semantics, pattern); EXPECT_TRUE(test.isZero()); @@ -1897,7 +1897,7 @@ APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.add(y, APFloat::rmNearestTiesToEven); - APFloat result(APFloat::IEEEsingle, SpecialCaseTests[i].result); + APFloat result(APFloat::IEEEsingle, StringRef(SpecialCaseTests[i].result)); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); @@ -2185,7 +2185,7 @@ APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.subtract(y, APFloat::rmNearestTiesToEven); - APFloat result(APFloat::IEEEsingle, SpecialCaseTests[i].result); + APFloat result(APFloat::IEEEsingle, StringRef(SpecialCaseTests[i].result)); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); @@ -2474,7 +2474,7 @@ APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.multiply(y, APFloat::rmNearestTiesToEven); - APFloat result(APFloat::IEEEsingle, SpecialCaseTests[i].result); + APFloat result(APFloat::IEEEsingle, StringRef(SpecialCaseTests[i].result)); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); @@ -2763,7 +2763,7 @@ APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.divide(y, APFloat::rmNearestTiesToEven); - APFloat result(APFloat::IEEEsingle, SpecialCaseTests[i].result); + APFloat result(APFloat::IEEEsingle, StringRef(SpecialCaseTests[i].result)); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); Index: llvm/unittests/ADT/APIntTest.cpp =================================================================== --- llvm/unittests/ADT/APIntTest.cpp +++ llvm/unittests/ADT/APIntTest.cpp @@ -421,7 +421,7 @@ // Lamdba to return an APInt by value, but also provide the raw value of the // allocated data. - auto getRValue = [](const char *HexString, uint64_t const *&RawData) { + auto getRValue = [](StringRef HexString, uint64_t const *&RawData) { APInt V(129, HexString, 16); RawData = V.getRawData(); return V; Index: llvm/unittests/ADT/FoldingSet.cpp =================================================================== --- llvm/unittests/ADT/FoldingSet.cpp +++ llvm/unittests/ADT/FoldingSet.cpp @@ -30,7 +30,7 @@ // An unaligned string. std::string str2 = ">" + str1; - b.AddString(str2.c_str() + 1); + b.AddString(StringRef(str2.c_str() + 1)); EXPECT_EQ(a.ComputeHash(), b.ComputeHash()); } Index: llvm/unittests/ADT/HashingTest.cpp =================================================================== --- llvm/unittests/ADT/HashingTest.cpp +++ llvm/unittests/ADT/HashingTest.cpp @@ -319,7 +319,7 @@ #endif }; for (unsigned i = 0; i < sizeof(golden_data)/sizeof(*golden_data); ++i) { - StringRef str = golden_data[i].s; + StringRef str(golden_data[i].s); hash_code hash = hash_combine_range(str.begin(), str.end()); #if 0 // Enable this to generate paste-able text for the above structure. std::string member_str = "\"" + str.str() + "\","; Index: llvm/unittests/ADT/StringMapTest.cpp =================================================================== --- llvm/unittests/ADT/StringMapTest.cpp +++ llvm/unittests/ADT/StringMapTest.cpp @@ -36,10 +36,10 @@ EXPECT_TRUE(testMap.begin() == testMap.end()); // Lookup tests - EXPECT_EQ(0u, testMap.count(testKey)); + EXPECT_EQ(0u, testMap.count(StringRef(testKey))); EXPECT_EQ(0u, testMap.count(StringRef(testKeyFirst, testKeyLength))); EXPECT_EQ(0u, testMap.count(testKeyStr)); - EXPECT_TRUE(testMap.find(testKey) == testMap.end()); + EXPECT_TRUE(testMap.find(StringRef(testKey)) == testMap.end()); EXPECT_TRUE(testMap.find(StringRef(testKeyFirst, testKeyLength)) == testMap.end()); EXPECT_TRUE(testMap.find(testKeyStr) == testMap.end()); @@ -59,10 +59,10 @@ EXPECT_TRUE(it == testMap.end()); // Lookup tests - EXPECT_EQ(1u, testMap.count(testKey)); + EXPECT_EQ(1u, testMap.count(StringRef(testKey))); EXPECT_EQ(1u, testMap.count(StringRef(testKeyFirst, testKeyLength))); EXPECT_EQ(1u, testMap.count(testKeyStr)); - EXPECT_TRUE(testMap.find(testKey) == testMap.begin()); + EXPECT_TRUE(testMap.find(StringRef(testKey)) == testMap.begin()); EXPECT_TRUE(testMap.find(StringRef(testKeyFirst, testKeyLength)) == testMap.begin()); EXPECT_TRUE(testMap.find(testKeyStr) == testMap.begin()); @@ -237,18 +237,18 @@ bool Inserted; StringMap::iterator NewIt; std::tie(NewIt, Inserted) = - testMap.insert(std::make_pair(testKeyFirst, testValue)); + testMap.insert(std::make_pair(StringRef(testKeyFirst), testValue)); EXPECT_EQ(1u, testMap.size()); - EXPECT_EQ(testValue, testMap[testKeyFirst]); - EXPECT_EQ(testKeyFirst, NewIt->first()); + EXPECT_EQ(testValue, testMap[StringRef(testKeyFirst)]); + EXPECT_EQ(StringRef(testKeyFirst), NewIt->first()); EXPECT_EQ(testValue, NewIt->second); EXPECT_TRUE(Inserted); StringMap::iterator ExistingIt; std::tie(ExistingIt, Inserted) = - testMap.insert(std::make_pair(testKeyFirst, testValue + 1)); + testMap.insert(std::make_pair(StringRef(testKeyFirst), testValue + 1)); EXPECT_EQ(1u, testMap.size()); - EXPECT_EQ(testValue, testMap[testKeyFirst]); + EXPECT_EQ(testValue, testMap[StringRef(testKeyFirst)]); EXPECT_FALSE(Inserted); EXPECT_EQ(NewIt, ExistingIt); } @@ -263,7 +263,7 @@ EXPECT_EQ(0u, t.getNumBuckets()); StringMap::iterator It = - t.insert(std::make_pair("abcdef", 42)).first; + t.insert(std::make_pair(StringRef("abcdef"), 42)).first; EXPECT_EQ(16u, t.getNumBuckets()); EXPECT_EQ("abcdef", It->first()); EXPECT_EQ(42u, It->second); @@ -278,7 +278,7 @@ TEST_F(StringMapTest, NonDefaultConstructable) { StringMap t; - t.insert(std::make_pair("Test", StringMapTestStruct(123))); + t.insert(std::make_pair(StringRef("Test"), StringMapTestStruct(123))); StringMap::iterator iter = t.find("Test"); ASSERT_NE(iter, t.end()); ASSERT_EQ(iter->second.i, 123); @@ -306,7 +306,7 @@ TEST_F(StringMapTest, MoveOnly) { StringMap t; - t.insert(std::make_pair("Test", MoveOnly(42))); + t.insert(std::make_pair(StringRef("Test"), MoveOnly(42))); StringRef Key = "Test"; StringMapEntry::Create(Key, MoveOnly(42)) ->Destroy(); @@ -365,7 +365,7 @@ TEST_F(StringMapTest, MoveDtor) { int InstanceCount = 0; StringMap A; - A.insert(std::make_pair("x", Countable(42, InstanceCount))); + A.insert(std::make_pair(StringRef("x"), Countable(42, InstanceCount))); ASSERT_EQ(InstanceCount, 1); auto I = A.find("x"); ASSERT_NE(I, A.end()); Index: llvm/unittests/ADT/StringRefTest.cpp =================================================================== --- llvm/unittests/ADT/StringRefTest.cpp +++ llvm/unittests/ADT/StringRefTest.cpp @@ -38,6 +38,10 @@ EXPECT_EQ("hello", StringRef("hello")); EXPECT_EQ("hello", StringRef("hello world", 5)); EXPECT_EQ("hello", StringRef(std::string("hello"))); + EXPECT_EQ(StringRef("hello\0\0\0\0").size(), 5u); + EXPECT_EQ(StringRef("hello\0\0\0\0"), StringRef("hello")); + EXPECT_EQ(StringRef("hello\0\0\0\0world").size(), 5u); + EXPECT_EQ(StringRef("hello\0\0\0\0world"), StringRef("hello")); } TEST(StringRefTest, Iteration) { @@ -671,46 +675,46 @@ uint64_t U64; for (size_t i = 0; i < array_lengthof(ConsumeUnsigned); ++i) { - StringRef Str = ConsumeUnsigned[i].Str; + StringRef Str(ConsumeUnsigned[i].Str); bool U8Success = Str.consumeInteger(0, U8); if (static_cast(ConsumeUnsigned[i].Expected) == ConsumeUnsigned[i].Expected) { ASSERT_FALSE(U8Success); EXPECT_EQ(U8, ConsumeUnsigned[i].Expected); - EXPECT_EQ(Str, ConsumeUnsigned[i].Leftover); + EXPECT_EQ(Str, StringRef(ConsumeUnsigned[i].Leftover)); } else { ASSERT_TRUE(U8Success); } - Str = ConsumeUnsigned[i].Str; + Str = StringRef(ConsumeUnsigned[i].Str); bool U16Success = Str.consumeInteger(0, U16); if (static_cast(ConsumeUnsigned[i].Expected) == ConsumeUnsigned[i].Expected) { ASSERT_FALSE(U16Success); EXPECT_EQ(U16, ConsumeUnsigned[i].Expected); - EXPECT_EQ(Str, ConsumeUnsigned[i].Leftover); + EXPECT_EQ(Str, StringRef(ConsumeUnsigned[i].Leftover)); } else { ASSERT_TRUE(U16Success); } - Str = ConsumeUnsigned[i].Str; + Str = StringRef(ConsumeUnsigned[i].Str); bool U32Success = Str.consumeInteger(0, U32); if (static_cast(ConsumeUnsigned[i].Expected) == ConsumeUnsigned[i].Expected) { ASSERT_FALSE(U32Success); EXPECT_EQ(U32, ConsumeUnsigned[i].Expected); - EXPECT_EQ(Str, ConsumeUnsigned[i].Leftover); + EXPECT_EQ(Str, StringRef(ConsumeUnsigned[i].Leftover)); } else { ASSERT_TRUE(U32Success); } - Str = ConsumeUnsigned[i].Str; + Str = StringRef(ConsumeUnsigned[i].Str); bool U64Success = Str.consumeInteger(0, U64); if (static_cast(ConsumeUnsigned[i].Expected) == ConsumeUnsigned[i].Expected) { ASSERT_FALSE(U64Success); EXPECT_EQ(U64, ConsumeUnsigned[i].Expected); - EXPECT_EQ(Str, ConsumeUnsigned[i].Leftover); + EXPECT_EQ(Str, StringRef(ConsumeUnsigned[i].Leftover)); } else { ASSERT_TRUE(U64Success); } @@ -724,53 +728,53 @@ int64_t S64; for (size_t i = 0; i < array_lengthof(ConsumeSigned); ++i) { - StringRef Str = ConsumeSigned[i].Str; + StringRef Str = StringRef(ConsumeSigned[i].Str); bool S8Success = Str.consumeInteger(0, S8); if (static_cast(ConsumeSigned[i].Expected) == ConsumeSigned[i].Expected) { ASSERT_FALSE(S8Success); EXPECT_EQ(S8, ConsumeSigned[i].Expected); - EXPECT_EQ(Str, ConsumeSigned[i].Leftover); + EXPECT_EQ(Str, StringRef(ConsumeSigned[i].Leftover)); } else { ASSERT_TRUE(S8Success); } - Str = ConsumeSigned[i].Str; + Str = StringRef(ConsumeSigned[i].Str); bool S16Success = Str.consumeInteger(0, S16); if (static_cast(ConsumeSigned[i].Expected) == ConsumeSigned[i].Expected) { ASSERT_FALSE(S16Success); EXPECT_EQ(S16, ConsumeSigned[i].Expected); - EXPECT_EQ(Str, ConsumeSigned[i].Leftover); + EXPECT_EQ(Str, StringRef(ConsumeSigned[i].Leftover)); } else { ASSERT_TRUE(S16Success); } - Str = ConsumeSigned[i].Str; + Str = StringRef(ConsumeSigned[i].Str); bool S32Success = Str.consumeInteger(0, S32); if (static_cast(ConsumeSigned[i].Expected) == ConsumeSigned[i].Expected) { ASSERT_FALSE(S32Success); EXPECT_EQ(S32, ConsumeSigned[i].Expected); - EXPECT_EQ(Str, ConsumeSigned[i].Leftover); + EXPECT_EQ(Str, StringRef(ConsumeSigned[i].Leftover)); } else { ASSERT_TRUE(S32Success); } - Str = ConsumeSigned[i].Str; + Str = StringRef(ConsumeSigned[i].Str); bool S64Success = Str.consumeInteger(0, S64); if (static_cast(ConsumeSigned[i].Expected) == ConsumeSigned[i].Expected) { ASSERT_FALSE(S64Success); EXPECT_EQ(S64, ConsumeSigned[i].Expected); - EXPECT_EQ(Str, ConsumeSigned[i].Leftover); + EXPECT_EQ(Str, StringRef(ConsumeSigned[i].Leftover)); } else { ASSERT_TRUE(S64Success); } } } -static const char *join_input[] = { "a", "b", "c" }; +static const StringRef join_input[] = {"a", "b", "c"}; static const char join_result1[] = "a"; static const char join_result2[] = "a:b:c"; static const char join_result3[] = "a::b::c"; Index: llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp =================================================================== --- llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp +++ llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp @@ -39,18 +39,18 @@ return BlockFrequencyInfo(F, *BPI, *LI); } std::unique_ptr makeLLVMModule() { - const char *ModuleStrig = "define i32 @f(i32 %x) {\n" - "bb0:\n" - " %y1 = icmp eq i32 %x, 0 \n" - " br i1 %y1, label %bb1, label %bb2 \n" - "bb1:\n" - " br label %bb3\n" - "bb2:\n" - " br label %bb3\n" - "bb3:\n" - " %y2 = phi i32 [0, %bb1], [1, %bb2] \n" - " ret i32 %y2\n" - "}\n"; + const char ModuleStrig[] = "define i32 @f(i32 %x) {\n" + "bb0:\n" + " %y1 = icmp eq i32 %x, 0 \n" + " br i1 %y1, label %bb1, label %bb2 \n" + "bb1:\n" + " br label %bb3\n" + "bb2:\n" + " br label %bb3\n" + "bb3:\n" + " %y2 = phi i32 [0, %bb1], [1, %bb2] \n" + " ret i32 %y2\n" + "}\n"; SMDiagnostic Err; return parseAssemblyString(ModuleStrig, Err, C); } Index: llvm/unittests/Analysis/CFGTest.cpp =================================================================== --- llvm/unittests/Analysis/CFGTest.cpp +++ llvm/unittests/Analysis/CFGTest.cpp @@ -29,7 +29,7 @@ // and ensuring it produces the correct answer each time. class IsPotentiallyReachableTest : public testing::Test { protected: - void ParseAssembly(const char *Assembly) { + void ParseAssembly(StringRef Assembly) { SMDiagnostic Error; M = parseAssemblyString(Assembly, Error, Context); @@ -349,7 +349,7 @@ ExpectPath(true); } -static const char *BranchInsideLoopIR = +static const char BranchInsideLoopIR[] = "declare i1 @switch()\n" "\n" "define void @test() {\n" Index: llvm/unittests/Analysis/CGSCCPassManagerTest.cpp =================================================================== --- llvm/unittests/Analysis/CGSCCPassManagerTest.cpp +++ llvm/unittests/Analysis/CGSCCPassManagerTest.cpp @@ -163,7 +163,7 @@ std::function Func; }; -std::unique_ptr parseIR(const char *IR) { +std::unique_ptr parseIR(StringRef IR) { // We just use a static context here. This is never called from multiple // threads so it is harmless no matter how it is implemented. We just need // the context to outlive the module which it does. Index: llvm/unittests/Analysis/LazyCallGraphTest.cpp =================================================================== --- llvm/unittests/Analysis/LazyCallGraphTest.cpp +++ llvm/unittests/Analysis/LazyCallGraphTest.cpp @@ -23,7 +23,7 @@ namespace { std::unique_ptr parseAssembly(LLVMContext &Context, - const char *Assembly) { + StringRef Assembly) { SMDiagnostic Error; std::unique_ptr M = parseAssemblyString(Assembly, Error, Context); Index: llvm/unittests/Analysis/LoopPassManagerTest.cpp =================================================================== --- llvm/unittests/Analysis/LoopPassManagerTest.cpp +++ llvm/unittests/Analysis/LoopPassManagerTest.cpp @@ -99,7 +99,7 @@ static StringRef name() { return "TestLoopInvalidatingPass"; } }; -std::unique_ptr parseIR(LLVMContext &C, const char *IR) { +std::unique_ptr parseIR(LLVMContext &C, StringRef IR) { SMDiagnostic Err; return parseAssemblyString(IR, Err, C); } Index: llvm/unittests/Analysis/UnrollAnalyzer.cpp =================================================================== --- llvm/unittests/Analysis/UnrollAnalyzer.cpp +++ llvm/unittests/Analysis/UnrollAnalyzer.cpp @@ -62,13 +62,13 @@ std::unique_ptr makeLLVMModule(LLVMContext &Context, UnrollAnalyzerTest *P, - const char *ModuleStr) { + StringRef ModuleStr) { SMDiagnostic Err; return parseAssemblyString(ModuleStr, Err, Context); } TEST(UnrollAnalyzerTest, BasicSimplifications) { - const char *ModuleStr = + const char ModuleStr[] = "target datalayout = \"e-m:o-i64:64-f80:128-n8:16:32:64-S128\"\n" "define i64 @propagate_loop_phis() {\n" "entry:\n" @@ -127,17 +127,19 @@ } TEST(UnrollAnalyzerTest, OuterLoopSimplification) { - const char *ModuleStr = + const char ModuleStr[] = "target datalayout = \"e-m:o-i64:64-f80:128-n8:16:32:64-S128\"\n" "define void @foo() {\n" "entry:\n" " br label %outer.loop\n" "outer.loop:\n" - " %iv.outer = phi i64 [ 0, %entry ], [ %iv.outer.next, %outer.loop.latch ]\n" + " %iv.outer = phi i64 [ 0, %entry ], [ %iv.outer.next, " + "%outer.loop.latch ]\n" " %iv.outer.next = add nuw nsw i64 %iv.outer, 1\n" " br label %inner.loop\n" "inner.loop:\n" - " %iv.inner = phi i64 [ 0, %outer.loop ], [ %iv.inner.next, %inner.loop ]\n" + " %iv.inner = phi i64 [ 0, %outer.loop ], [ %iv.inner.next, %inner.loop " + "]\n" " %iv.inner.next = add nuw nsw i64 %iv.inner, 1\n" " %exitcond.inner = icmp eq i64 %iv.inner.next, 1000\n" " br i1 %exitcond.inner, label %outer.loop.latch, label %inner.loop\n" @@ -178,7 +180,7 @@ EXPECT_TRUE(I2 == SimplifiedValuesVector[0].end()); } TEST(UnrollAnalyzerTest, CmpSimplifications) { - const char *ModuleStr = + const char ModuleStr[] = "target datalayout = \"e-m:o-i64:64-f80:128-n8:16:32:64-S128\"\n" "define void @branch_iv_trunc() {\n" "entry:\n" @@ -222,7 +224,7 @@ EXPECT_EQ(cast((*I2).second)->getZExtValue(), 1U); } TEST(UnrollAnalyzerTest, PtrCmpSimplifications) { - const char *ModuleStr = + const char ModuleStr[] = "target datalayout = \"e-m:o-i64:64-f80:128-n8:16:32:64-S128\"\n" "define void @ptr_cmp(i8 *%a) {\n" "entry:\n" @@ -264,16 +266,18 @@ EXPECT_EQ(cast((*I1).second)->getZExtValue(), 0U); } TEST(UnrollAnalyzerTest, CastSimplifications) { - const char *ModuleStr = + const char ModuleStr[] = "target datalayout = \"e-m:o-i64:64-f80:128-n8:16:32:64-S128\"\n" - "@known_constant = internal unnamed_addr constant [10 x i32] [i32 0, i32 1, i32 0, i32 1, i32 0, i32 259, i32 0, i32 1, i32 0, i32 1], align 16\n" + "@known_constant = internal unnamed_addr constant [10 x i32] [i32 0, i32 " + "1, i32 0, i32 1, i32 0, i32 259, i32 0, i32 1, i32 0, i32 1], align 16\n" "define void @const_load_cast() {\n" "entry:\n" " br label %loop\n" "\n" "loop:\n" " %iv = phi i64 [ 0, %entry ], [ %inc, %loop ]\n" - " %array_const_idx = getelementptr inbounds [10 x i32], [10 x i32]* @known_constant, i64 0, i64 %iv\n" + " %array_const_idx = getelementptr inbounds [10 x i32], [10 x i32]* " + "@known_constant, i64 0, i64 %iv\n" " %const_array_element = load i32, i32* %array_const_idx, align 4\n" " %se = sext i32 %const_array_element to i64\n" " %ze = zext i32 %const_array_element to i64\n" Index: llvm/unittests/Analysis/ValueTrackingTest.cpp =================================================================== --- llvm/unittests/Analysis/ValueTrackingTest.cpp +++ llvm/unittests/Analysis/ValueTrackingTest.cpp @@ -23,7 +23,7 @@ class MatchSelectPatternTest : public testing::Test { protected: - void parseAssembly(const char *Assembly) { + void parseAssembly(StringRef Assembly) { SMDiagnostic Error; M = parseAssemblyString(Assembly, Error, Context); Index: llvm/unittests/Bitcode/BitReaderTest.cpp =================================================================== --- llvm/unittests/Bitcode/BitReaderTest.cpp +++ llvm/unittests/Bitcode/BitReaderTest.cpp @@ -30,7 +30,7 @@ namespace { std::unique_ptr parseAssembly(LLVMContext &Context, - const char *Assembly) { + StringRef Assembly) { SMDiagnostic Error; std::unique_ptr M = parseAssemblyString(Assembly, Error, Context); @@ -53,7 +53,7 @@ static std::unique_ptr getLazyModuleFromAssembly(LLVMContext &Context, SmallString<1024> &Mem, - const char *Assembly) { + StringRef Assembly) { writeModuleToBuffer(parseAssembly(Context, Assembly), Mem); std::unique_ptr Buffer = MemoryBuffer::getMemBuffer(Mem.str(), "test", false); @@ -81,7 +81,7 @@ static std::unique_ptr getStreamedModuleFromAssembly(LLVMContext &Context, SmallString<1024> &Mem, - const char *Assembly) { + StringRef Assembly) { writeModuleToBuffer(parseAssembly(Context, Assembly), Mem); std::unique_ptr Buffer = MemoryBuffer::getMemBuffer(Mem.str(), "test", false); Index: llvm/unittests/ExecutionEngine/MCJIT/MCJITCAPITest.cpp =================================================================== --- llvm/unittests/ExecutionEngine/MCJIT/MCJITCAPITest.cpp +++ llvm/unittests/ExecutionEngine/MCJIT/MCJITCAPITest.cpp @@ -35,8 +35,8 @@ unsigned sectionID, const char *sectionName) { didCallAllocateCodeSection = true; - return static_cast(object)->allocateCodeSection( - size, alignment, sectionID, sectionName); + return static_cast(object)->allocateCodeSection( + size, alignment, sectionID, StringRef(sectionName)); } static uint8_t *roundTripAllocateDataSection(void *object, uintptr_t size, @@ -46,8 +46,8 @@ LLVMBool isReadOnly) { if (!strcmp(sectionName, "__compact_unwind")) didAllocateCompactUnwindSection = true; - return static_cast(object)->allocateDataSection( - size, alignment, sectionID, sectionName, isReadOnly); + return static_cast(object)->allocateDataSection( + size, alignment, sectionID, StringRef(sectionName), isReadOnly); } static LLVMBool roundTripFinalizeMemory(void *object, char **errMsg) { Index: llvm/unittests/ExecutionEngine/MCJIT/MCJITMultipleModuleTest.cpp =================================================================== --- llvm/unittests/ExecutionEngine/MCJIT/MCJITMultipleModuleTest.cpp +++ llvm/unittests/ExecutionEngine/MCJIT/MCJITMultipleModuleTest.cpp @@ -416,8 +416,8 @@ createJIT(std::move(A)); TheJIT->addModule(std::move(B)); - EXPECT_EQ(FA, TheJIT->FindFunctionNamed(FA->getName().data())); - EXPECT_EQ(FB1, TheJIT->FindFunctionNamed(FB1->getName().data())); + EXPECT_EQ(FA, TheJIT->FindFunctionNamed(FA->getName())); + EXPECT_EQ(FB1, TheJIT->FindFunctionNamed(FB1->getName())); } } // end anonymous namespace Index: llvm/unittests/ExecutionEngine/MCJIT/MCJITTestAPICommon.h =================================================================== --- llvm/unittests/ExecutionEngine/MCJIT/MCJITTestAPICommon.h +++ llvm/unittests/ExecutionEngine/MCJIT/MCJITTestAPICommon.h @@ -67,7 +67,7 @@ // If ARCH has sub-arch support, find it SmallVectorImpl::const_iterator I = SupportedSubArchs.begin(); for(; I != SupportedSubArchs.end(); ++I) - if (Host.getArchName().startswith(I->c_str())) + if (Host.getArchName().startswith(*I)) return true; return false; Index: llvm/unittests/IR/DominatorTreeTest.cpp =================================================================== --- llvm/unittests/IR/DominatorTreeTest.cpp +++ llvm/unittests/IR/DominatorTreeTest.cpp @@ -216,29 +216,29 @@ char DPass::ID = 0; std::unique_ptr makeLLVMModule(LLVMContext &Context, DPass *P) { - const char *ModuleStrig = - "declare i32 @g()\n" \ - "define void @f(i32 %x) personality i32 ()* @g {\n" \ - "bb0:\n" \ - " %y1 = add i32 %x, 1\n" \ - " %y2 = add i32 %x, 1\n" \ - " %y3 = invoke i32 @g() to label %bb1 unwind label %bb2\n" \ - "bb1:\n" \ - " %y4 = add i32 %x, 1\n" \ - " br label %bb4\n" \ - "bb2:\n" \ - " %y5 = landingpad i32\n" \ - " cleanup\n" \ - " br label %bb4\n" \ - "bb3:\n" \ - " %y6 = add i32 %x, 1\n" \ - " %y7 = add i32 %x, 1\n" \ - " ret void\n" \ - "bb4:\n" \ - " %y8 = phi i32 [0, %bb2], [%y4, %bb1]\n" - " %y9 = phi i32 [0, %bb2], [%y4, %bb1]\n" - " ret void\n" \ - "}\n"; + const char ModuleStrig[] = + "declare i32 @g()\n" + "define void @f(i32 %x) personality i32 ()* @g {\n" + "bb0:\n" + " %y1 = add i32 %x, 1\n" + " %y2 = add i32 %x, 1\n" + " %y3 = invoke i32 @g() to label %bb1 unwind label %bb2\n" + "bb1:\n" + " %y4 = add i32 %x, 1\n" + " br label %bb4\n" + "bb2:\n" + " %y5 = landingpad i32\n" + " cleanup\n" + " br label %bb4\n" + "bb3:\n" + " %y6 = add i32 %x, 1\n" + " %y7 = add i32 %x, 1\n" + " ret void\n" + "bb4:\n" + " %y8 = phi i32 [0, %bb2], [%y4, %bb1]\n" + " %y9 = phi i32 [0, %bb2], [%y4, %bb1]\n" + " ret void\n" + "}\n"; SMDiagnostic Err; return parseAssemblyString(ModuleStrig, Err, Context); } Index: llvm/unittests/IR/IntrinsicsTest.cpp =================================================================== --- llvm/unittests/IR/IntrinsicsTest.cpp +++ llvm/unittests/IR/IntrinsicsTest.cpp @@ -14,12 +14,8 @@ namespace { -static const char *const NameTable1[] = { - "llvm.foo", - "llvm.foo.a", - "llvm.foo.b", - "llvm.foo.b.a", - "llvm.foo.c", +static StringRef NameTable1[] = { + "llvm.foo", "llvm.foo.a", "llvm.foo.b", "llvm.foo.b.a", "llvm.foo.c", }; TEST(IntrinNameLookup, Basic) { Index: llvm/unittests/IR/MetadataTest.cpp =================================================================== --- llvm/unittests/IR/MetadataTest.cpp +++ llvm/unittests/IR/MetadataTest.cpp @@ -2226,7 +2226,7 @@ MDNode *n2 = MDNode::get(Context, V2); Module M("MyModule", Context); - const char *Name = "llvm.NMD1"; + const char Name[] = "llvm.NMD1"; NamedMDNode *NMD = M.getOrInsertNamedMetadata(Name); NMD->addOperand(n); NMD->addOperand(n2); Index: llvm/unittests/IR/PassManagerTest.cpp =================================================================== --- llvm/unittests/IR/PassManagerTest.cpp +++ llvm/unittests/IR/PassManagerTest.cpp @@ -155,7 +155,7 @@ StringRef Name; }; -std::unique_ptr parseIR(LLVMContext &Context, const char *IR) { +std::unique_ptr parseIR(LLVMContext &Context, StringRef IR) { SMDiagnostic Err; return parseAssemblyString(IR, Err, Context); } Index: llvm/unittests/IR/UseTest.cpp =================================================================== --- llvm/unittests/IR/UseTest.cpp +++ llvm/unittests/IR/UseTest.cpp @@ -24,18 +24,18 @@ TEST(UseTest, sort) { LLVMContext C; - const char *ModuleString = "define void @f(i32 %x) {\n" - "entry:\n" - " %v0 = add i32 %x, 0\n" - " %v2 = add i32 %x, 2\n" - " %v5 = add i32 %x, 5\n" - " %v1 = add i32 %x, 1\n" - " %v3 = add i32 %x, 3\n" - " %v7 = add i32 %x, 7\n" - " %v6 = add i32 %x, 6\n" - " %v4 = add i32 %x, 4\n" - " ret void\n" - "}\n"; + const char ModuleString[] = "define void @f(i32 %x) {\n" + "entry:\n" + " %v0 = add i32 %x, 0\n" + " %v2 = add i32 %x, 2\n" + " %v5 = add i32 %x, 5\n" + " %v1 = add i32 %x, 1\n" + " %v3 = add i32 %x, 3\n" + " %v7 = add i32 %x, 7\n" + " %v6 = add i32 %x, 6\n" + " %v4 = add i32 %x, 4\n" + " ret void\n" + "}\n"; SMDiagnostic Err; char vnbuf[8]; std::unique_ptr M = parseAssemblyString(ModuleString, Err, C); @@ -69,18 +69,18 @@ TEST(UseTest, reverse) { LLVMContext C; - const char *ModuleString = "define void @f(i32 %x) {\n" - "entry:\n" - " %v0 = add i32 %x, 0\n" - " %v2 = add i32 %x, 2\n" - " %v5 = add i32 %x, 5\n" - " %v1 = add i32 %x, 1\n" - " %v3 = add i32 %x, 3\n" - " %v7 = add i32 %x, 7\n" - " %v6 = add i32 %x, 6\n" - " %v4 = add i32 %x, 4\n" - " ret void\n" - "}\n"; + const char ModuleString[] = "define void @f(i32 %x) {\n" + "entry:\n" + " %v0 = add i32 %x, 0\n" + " %v2 = add i32 %x, 2\n" + " %v5 = add i32 %x, 5\n" + " %v1 = add i32 %x, 1\n" + " %v3 = add i32 %x, 3\n" + " %v7 = add i32 %x, 7\n" + " %v6 = add i32 %x, 6\n" + " %v4 = add i32 %x, 4\n" + " ret void\n" + "}\n"; SMDiagnostic Err; char vnbuf[8]; std::unique_ptr M = parseAssemblyString(ModuleString, Err, C); Index: llvm/unittests/IR/UserTest.cpp =================================================================== --- llvm/unittests/IR/UserTest.cpp +++ llvm/unittests/IR/UserTest.cpp @@ -22,48 +22,48 @@ TEST(UserTest, ValueOpIteration) { LLVMContext C; - const char *ModuleString = "define void @f(i32 %x, i32 %y) {\n" - "entry:\n" - " switch i32 undef, label %s0\n" - " [ i32 1, label %s1\n" - " i32 2, label %s2\n" - " i32 3, label %s3\n" - " i32 4, label %s4\n" - " i32 5, label %s5\n" - " i32 6, label %s6\n" - " i32 7, label %s7\n" - " i32 8, label %s8\n" - " i32 9, label %s9 ]\n" - "\n" - "s0:\n" - " br label %exit\n" - "s1:\n" - " br label %exit\n" - "s2:\n" - " br label %exit\n" - "s3:\n" - " br label %exit\n" - "s4:\n" - " br label %exit\n" - "s5:\n" - " br label %exit\n" - "s6:\n" - " br label %exit\n" - "s7:\n" - " br label %exit\n" - "s8:\n" - " br label %exit\n" - "s9:\n" - " br label %exit\n" - "\n" - "exit:\n" - " %phi = phi i32 [ 0, %s0 ], [ 1, %s1 ],\n" - " [ 2, %s2 ], [ 3, %s3 ],\n" - " [ 4, %s4 ], [ 5, %s5 ],\n" - " [ 6, %s6 ], [ 7, %s7 ],\n" - " [ 8, %s8 ], [ 9, %s9 ]\n" - " ret void\n" - "}\n"; + const char ModuleString[] = "define void @f(i32 %x, i32 %y) {\n" + "entry:\n" + " switch i32 undef, label %s0\n" + " [ i32 1, label %s1\n" + " i32 2, label %s2\n" + " i32 3, label %s3\n" + " i32 4, label %s4\n" + " i32 5, label %s5\n" + " i32 6, label %s6\n" + " i32 7, label %s7\n" + " i32 8, label %s8\n" + " i32 9, label %s9 ]\n" + "\n" + "s0:\n" + " br label %exit\n" + "s1:\n" + " br label %exit\n" + "s2:\n" + " br label %exit\n" + "s3:\n" + " br label %exit\n" + "s4:\n" + " br label %exit\n" + "s5:\n" + " br label %exit\n" + "s6:\n" + " br label %exit\n" + "s7:\n" + " br label %exit\n" + "s8:\n" + " br label %exit\n" + "s9:\n" + " br label %exit\n" + "\n" + "exit:\n" + " %phi = phi i32 [ 0, %s0 ], [ 1, %s1 ],\n" + " [ 2, %s2 ], [ 3, %s3 ],\n" + " [ 4, %s4 ], [ 5, %s5 ],\n" + " [ 6, %s6 ], [ 7, %s7 ],\n" + " [ 8, %s8 ], [ 9, %s9 ]\n" + " ret void\n" + "}\n"; SMDiagnostic Err; std::unique_ptr M = parseAssemblyString(ModuleString, Err, C); Index: llvm/unittests/IR/ValueTest.cpp =================================================================== --- llvm/unittests/IR/ValueTest.cpp +++ llvm/unittests/IR/ValueTest.cpp @@ -22,18 +22,18 @@ TEST(ValueTest, UsedInBasicBlock) { LLVMContext C; - const char *ModuleString = "define void @f(i32 %x, i32 %y) {\n" - "bb0:\n" - " %y1 = add i32 %y, 1\n" - " %y2 = add i32 %y, 1\n" - " %y3 = add i32 %y, 1\n" - " %y4 = add i32 %y, 1\n" - " %y5 = add i32 %y, 1\n" - " %y6 = add i32 %y, 1\n" - " %y7 = add i32 %y, 1\n" - " %y8 = add i32 %x, 1\n" - " ret void\n" - "}\n"; + const char ModuleString[] = "define void @f(i32 %x, i32 %y) {\n" + "bb0:\n" + " %y1 = add i32 %y, 1\n" + " %y2 = add i32 %y, 1\n" + " %y3 = add i32 %y, 1\n" + " %y4 = add i32 %y, 1\n" + " %y5 = add i32 %y, 1\n" + " %y6 = add i32 %y, 1\n" + " %y7 = add i32 %y, 1\n" + " %y8 = add i32 %x, 1\n" + " ret void\n" + "}\n"; SMDiagnostic Err; std::unique_ptr M = parseAssemblyString(ModuleString, Err, C); @@ -112,12 +112,12 @@ // without a slot tracker. LLVMContext C; - const char *ModuleString = "define void @f(i32 %x, i32 %y) {\n" - "entry:\n" - " %0 = add i32 %y, 1\n" - " %1 = add i32 %y, 1\n" - " ret void\n" - "}\n"; + const char ModuleString[] = "define void @f(i32 %x, i32 %y) {\n" + "entry:\n" + " %0 = add i32 %y, 1\n" + " %1 = add i32 %y, 1\n" + " ret void\n" + "}\n"; SMDiagnostic Err; std::unique_ptr M = parseAssemblyString(ModuleString, Err, C); @@ -178,14 +178,14 @@ TEST(ValueTest, getLocalSlots) { // Verify that the getLocalSlot method returns the correct slot numbers. LLVMContext C; - const char *ModuleString = "define void @f(i32 %x, i32 %y) {\n" - "entry:\n" - " %0 = add i32 %y, 1\n" - " %1 = add i32 %y, 1\n" - " br label %2\n" - "\n" - " ret void\n" - "}\n"; + const char ModuleString[] = "define void @f(i32 %x, i32 %y) {\n" + "entry:\n" + " %0 = add i32 %y, 1\n" + " %1 = add i32 %y, 1\n" + " br label %2\n" + "\n" + " ret void\n" + "}\n"; SMDiagnostic Err; std::unique_ptr M = parseAssemblyString(ModuleString, Err, C); @@ -213,14 +213,14 @@ #if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG) TEST(ValueTest, getLocalSlotDeath) { LLVMContext C; - const char *ModuleString = "define void @f(i32 %x, i32 %y) {\n" - "entry:\n" - " %0 = add i32 %y, 1\n" - " %1 = add i32 %y, 1\n" - " br label %2\n" - "\n" - " ret void\n" - "}\n"; + const char ModuleString[] = "define void @f(i32 %x, i32 %y) {\n" + "entry:\n" + " %0 = add i32 %y, 1\n" + " %1 = add i32 %y, 1\n" + " br label %2\n" + "\n" + " ret void\n" + "}\n"; SMDiagnostic Err; std::unique_ptr M = parseAssemblyString(ModuleString, Err, C); Index: llvm/unittests/Linker/LinkModulesTest.cpp =================================================================== --- llvm/unittests/Linker/LinkModulesTest.cpp +++ llvm/unittests/Linker/LinkModulesTest.cpp @@ -187,12 +187,12 @@ LLVMContext C; SMDiagnostic Err; - const char *M1Str = "%t = type {i32}\n" - "@t1 = weak global %t zeroinitializer\n"; + const char M1Str[] = "%t = type {i32}\n" + "@t1 = weak global %t zeroinitializer\n"; std::unique_ptr M1 = parseAssemblyString(M1Str, Err, C); - const char *M2Str = "%t = type {i32}\n" - "@t2 = weak global %t zeroinitializer\n"; + const char M2Str[] = "%t = type {i32}\n" + "@t2 = weak global %t zeroinitializer\n"; std::unique_ptr M2 = parseAssemblyString(M2Str, Err, C); Ctx.setDiagnosticHandler(expectNoDiags); @@ -237,18 +237,18 @@ LLVMContext C; SMDiagnostic Err; - const char *SrcStr = "define void @foo() !attach !0 {\n" - "entry:\n" - " call void @llvm.md(metadata !1)\n" - " ret void, !attach !2\n" - "}\n" - "declare void @llvm.md(metadata)\n" - "!named = !{!3, !4}\n" - "!0 = distinct !{}\n" - "!1 = distinct !{}\n" - "!2 = distinct !{}\n" - "!3 = distinct !{}\n" - "!4 = !{!3}\n"; + const char SrcStr[] = "define void @foo() !attach !0 {\n" + "entry:\n" + " call void @llvm.md(metadata !1)\n" + " ret void, !attach !2\n" + "}\n" + "declare void @llvm.md(metadata)\n" + "!named = !{!3, !4}\n" + "!0 = distinct !{}\n" + "!1 = distinct !{}\n" + "!2 = distinct !{}\n" + "!3 = distinct !{}\n" + "!4 = !{!3}\n"; std::unique_ptr Src = parseAssemblyString(SrcStr, Err, C); assert(Src); @@ -314,21 +314,25 @@ // "struct.rtx_def" type. In the module loaded the second (Bar) this type will // be renamed to "struct.rtx_def.0". Check that the intrinsics which have this // type in the signature are properly remangled. - const char *FooStr = - "%struct.rtx_def = type { i16 }\n" - "define void @foo(%struct.rtx_def* %a, i8 %b, i32 %c) {\n" - " call void @llvm.memset.p0struct.rtx_def.i32(%struct.rtx_def* %a, i8 %b, i32 %c, i32 4, i1 true)\n" - " ret void\n" - "}\n" - "declare void @llvm.memset.p0struct.rtx_def.i32(%struct.rtx_def*, i8, i32, i32, i1)\n"; - - const char *BarStr = - "%struct.rtx_def = type { i16 }\n" - "define void @bar(%struct.rtx_def* %a, i8 %b, i32 %c) {\n" - " call void @llvm.memset.p0struct.rtx_def.i32(%struct.rtx_def* %a, i8 %b, i32 %c, i32 4, i1 true)\n" - " ret void\n" - "}\n" - "declare void @llvm.memset.p0struct.rtx_def.i32(%struct.rtx_def*, i8, i32, i32, i1)\n"; + const char FooStr[] = + "%struct.rtx_def = type { i16 }\n" + "define void @foo(%struct.rtx_def* %a, i8 %b, i32 %c) {\n" + " call void @llvm.memset.p0struct.rtx_def.i32(%struct.rtx_def* %a, i8 " + "%b, i32 %c, i32 4, i1 true)\n" + " ret void\n" + "}\n" + "declare void @llvm.memset.p0struct.rtx_def.i32(%struct.rtx_def*, i8, " + "i32, i32, i1)\n"; + + const char BarStr[] = + "%struct.rtx_def = type { i16 }\n" + "define void @bar(%struct.rtx_def* %a, i8 %b, i32 %c) {\n" + " call void @llvm.memset.p0struct.rtx_def.i32(%struct.rtx_def* %a, i8 " + "%b, i32 %c, i32 4, i1 true)\n" + " ret void\n" + "}\n" + "declare void @llvm.memset.p0struct.rtx_def.i32(%struct.rtx_def*, i8, " + "i32, i32, i1)\n"; std::unique_ptr Foo = parseAssemblyString(FooStr, Err, C); assert(Foo); Index: llvm/unittests/MC/DwarfLineTables.cpp =================================================================== --- llvm/unittests/MC/DwarfLineTables.cpp +++ llvm/unittests/MC/DwarfLineTables.cpp @@ -21,7 +21,7 @@ namespace { struct Context { - const char *Triple = "x86_64-pc-linux"; + StringRef Triple = "x86_64-pc-linux"; std::unique_ptr MRI; std::unique_ptr MAI; std::unique_ptr Ctx; Index: llvm/unittests/MI/LiveIntervalTest.cpp =================================================================== --- llvm/unittests/MI/LiveIntervalTest.cpp +++ llvm/unittests/MI/LiveIntervalTest.cpp @@ -51,8 +51,10 @@ } std::unique_ptr parseMIR(LLVMContext &Context, - legacy::PassManagerBase &PM, std::unique_ptr &MIR, - const TargetMachine &TM, StringRef MIRCode, const char *FuncName) { + legacy::PassManagerBase &PM, + std::unique_ptr &MIR, + const TargetMachine &TM, StringRef MIRCode, + StringRef FuncName) { SMDiagnostic Diagnostic; std::unique_ptr MBuffer = MemoryBuffer::getMemBuffer(MIRCode); MIR = createMIRParser(std::move(MBuffer), Context); Index: llvm/unittests/ProfileData/CoverageMappingTest.cpp =================================================================== --- llvm/unittests/ProfileData/CoverageMappingTest.cpp +++ llvm/unittests/ProfileData/CoverageMappingTest.cpp @@ -267,7 +267,7 @@ } TEST_P(CoverageMappingTest, correct_deserialize_for_more_than_two_files) { - const char *FileNames[] = {"bar", "baz", "foo"}; + const char FileNames[][4] = {"bar", "baz", "foo"}; static const unsigned N = array_lengthof(FileNames); startFunction("func", 0x1234); @@ -295,7 +295,7 @@ InstrProfRecord Record("func", 0x1234, {0}); NoError(ProfileWriter.addRecord(std::move(Record))); - const char *FileNames[] = {"bar", "baz", "foo"}; + const char FileNames[][4] = {"bar", "baz", "foo"}; static const unsigned N = array_lengthof(FileNames); startFunction("func", 0x1234); Index: llvm/unittests/Support/ProgramTest.cpp =================================================================== --- llvm/unittests/Support/ProgramTest.cpp +++ llvm/unittests/Support/ProgramTest.cpp @@ -328,8 +328,8 @@ SmallString<128> file_pathname(TestDirectory); path::append(file_pathname, "international-file.txt"); // Only on Windows we should encode in UTF16. For other systems, use UTF8 - ASSERT_NO_ERROR(sys::writeFileWithEncoding(file_pathname.c_str(), utf8_text, - sys::WEM_UTF16)); + ASSERT_NO_ERROR( + sys::writeFileWithEncoding(file_pathname, utf8_text, sys::WEM_UTF16)); int fd = 0; ASSERT_NO_ERROR(fs::openFileForRead(file_pathname.c_str(), fd)); #if defined(LLVM_ON_WIN32) Index: llvm/unittests/Support/TargetParserTest.cpp =================================================================== --- llvm/unittests/Support/TargetParserTest.cpp +++ llvm/unittests/Support/TargetParserTest.cpp @@ -23,7 +23,7 @@ }; template struct ArchNames { - const char *Name; + StringRef Name; unsigned DefaultFPU; unsigned ArchBaseExtensions; T ID; @@ -45,7 +45,7 @@ }; template struct CpuNames { - const char *Name; + StringRef Name; T ID; unsigned DefaultFPU; unsigned DefaultExt; @@ -63,7 +63,7 @@ #undef ARM_CPU_NAME }; -const char *ARMArch[] = { +StringRef ARMArch[] = { "armv2", "armv2a", "armv3", "armv3m", "armv4", "armv4t", "armv5", "armv5t", "armv5e", "armv5te", "armv5tej", "armv6", "armv6j", "armv6k", "armv6hl", @@ -209,22 +209,22 @@ } TEST(TargetParserTest, ARMArchExtFeature) { - const char *ArchExt[][4] = {{"crc", "nocrc", "+crc", "-crc"}, - {"crypto", "nocrypto", "+crypto", "-crypto"}, - {"dsp", "nodsp", "+dsp", "-dsp"}, - {"fp", "nofp", nullptr, nullptr}, - {"idiv", "noidiv", nullptr, nullptr}, - {"mp", "nomp", nullptr, nullptr}, - {"simd", "nosimd", nullptr, nullptr}, - {"sec", "nosec", nullptr, nullptr}, - {"virt", "novirt", nullptr, nullptr}, - {"fp16", "nofp16", "+fullfp16", "-fullfp16"}, - {"ras", "noras", "+ras", "-ras"}, - {"os", "noos", nullptr, nullptr}, - {"iwmmxt", "noiwmmxt", nullptr, nullptr}, - {"iwmmxt2", "noiwmmxt2", nullptr, nullptr}, - {"maverick", "maverick", nullptr, nullptr}, - {"xscale", "noxscale", nullptr, nullptr}}; + StringRef ArchExt[][4] = {{"crc", "nocrc", "+crc", "-crc"}, + {"crypto", "nocrypto", "+crypto", "-crypto"}, + {"dsp", "nodsp", "+dsp", "-dsp"}, + {"fp", "nofp", StringRef(), StringRef()}, + {"idiv", "noidiv", StringRef(), StringRef()}, + {"mp", "nomp", StringRef(), StringRef()}, + {"simd", "nosimd", StringRef(), StringRef()}, + {"sec", "nosec", StringRef(), StringRef()}, + {"virt", "novirt", StringRef(), StringRef()}, + {"fp16", "nofp16", "+fullfp16", "-fullfp16"}, + {"ras", "noras", "+ras", "-ras"}, + {"os", "noos", StringRef(), StringRef()}, + {"iwmmxt", "noiwmmxt", StringRef(), StringRef()}, + {"iwmmxt2", "noiwmmxt2", StringRef(), StringRef()}, + {"maverick", "maverick", StringRef(), StringRef()}, + {"xscale", "noxscale", StringRef(), StringRef()}}; for (unsigned i = 0; i < array_lengthof(ArchExt); i++) { EXPECT_EQ(StringRef(ArchExt[i][2]), ARM::getArchExtFeature(ArchExt[i][0])); @@ -285,7 +285,7 @@ TEST(TargetParserTest, ARMparseArch) { for (unsigned i = 0; i < array_lengthof(ARMArch); i++) - EXPECT_NE(ARM::AEK_INVALID, ARM::parseArch(ARMArch[i])); + EXPECT_NE(ARM::AEK_INVALID, ARM::parseArch(StringRef(ARMArch[i]))); } TEST(TargetParserTest, ARMparseArchExt) { @@ -295,11 +295,11 @@ "maverick", "xscale"}; for (unsigned i = 0; i < array_lengthof(ArchExt); i++) - EXPECT_NE(ARM::AEK_INVALID, ARM::parseArchExt(ArchExt[i])); + EXPECT_NE(ARM::AEK_INVALID, ARM::parseArchExt(StringRef(ArchExt[i]))); } TEST(TargetParserTest, ARMparseCPUArch) { - const char *CPU[] = { + StringRef CPU[] = { "arm2", "arm3", "arm6", "arm7m", "arm8", "arm810", "strongarm", "strongarm110", "strongarm1100", "strongarm1110", "arm7tdmi", "arm7tdmi-s", @@ -317,7 +317,7 @@ "cortex-r5", "cortex-r7", "cortex-r8", "sc300", "cortex-m3", "cortex-m4", "cortex-m7", "cortex-a32", "cortex-a35", "cortex-a53", "cortex-a57", "cortex-a72", - "cortex-a73", "cyclone", "exynos-m1", "exynos-m2", + "cortex-a73", "cyclone", "exynos-m1", "exynos-m2", "iwmmxt", "xscale", "swift", "cortex-r52"}; for (const auto &ARMCPUName : kARMCPUNames) { @@ -374,35 +374,37 @@ TEST(TargetParserTest, ARMparseArchProfile) { for (unsigned i = 0; i < array_lengthof(ARMArch); i++) { - switch (ARM::parseArch(ARMArch[i])) { + StringRef Arch(ARMArch[i]); + switch (ARM::parseArch(Arch)) { case ARM::AK_ARMV6M: case ARM::AK_ARMV7M: case ARM::AK_ARMV7EM: case ARM::AK_ARMV8MMainline: case ARM::AK_ARMV8MBaseline: - EXPECT_EQ(ARM::PK_M, ARM::parseArchProfile(ARMArch[i])); + EXPECT_EQ(ARM::PK_M, ARM::parseArchProfile(Arch)); continue; case ARM::AK_ARMV7R: - EXPECT_EQ(ARM::PK_R, ARM::parseArchProfile(ARMArch[i])); + EXPECT_EQ(ARM::PK_R, ARM::parseArchProfile(Arch)); continue; case ARM::AK_ARMV7A: case ARM::AK_ARMV7K: case ARM::AK_ARMV8A: case ARM::AK_ARMV8_1A: case ARM::AK_ARMV8_2A: - EXPECT_EQ(ARM::PK_A, ARM::parseArchProfile(ARMArch[i])); + EXPECT_EQ(ARM::PK_A, ARM::parseArchProfile(Arch)); continue; } - EXPECT_EQ(ARM::PK_INVALID, ARM::parseArchProfile(ARMArch[i])); + EXPECT_EQ(ARM::PK_INVALID, ARM::parseArchProfile(Arch)); } } TEST(TargetParserTest, ARMparseArchVersion) { for (unsigned i = 0; i < array_lengthof(ARMArch); i++) if (((std::string)ARMArch[i]).substr(0, 4) == "armv") - EXPECT_EQ((ARMArch[i][4] - 48u), ARM::parseArchVersion(ARMArch[i])); + EXPECT_EQ((ARMArch[i][4] - 48u), + ARM::parseArchVersion(StringRef(ARMArch[i]))); else - EXPECT_EQ(5u, ARM::parseArchVersion(ARMArch[i])); + EXPECT_EQ(5u, ARM::parseArchVersion(StringRef(ARMArch[i]))); } TEST(TargetParserTest, AArch64DefaultFPU) { @@ -498,13 +500,13 @@ } TEST(TargetParserTest, AArch64ArchExtFeature) { - const char *ArchExt[][4] = {{"crc", "nocrc", "+crc", "-crc"}, - {"crypto", "nocrypto", "+crypto", "-crypto"}, - {"fp", "nofp", "+fp-armv8", "-fp-armv8"}, - {"simd", "nosimd", "+neon", "-neon"}, - {"fp16", "nofp16", "+fullfp16", "-fullfp16"}, - {"profile", "noprofile", "+spe", "-spe"}, - {"ras", "noras", "+ras", "-ras"}}; + StringRef ArchExt[][4] = {{"crc", "nocrc", "+crc", "-crc"}, + {"crypto", "nocrypto", "+crypto", "-crypto"}, + {"fp", "nofp", "+fp-armv8", "-fp-armv8"}, + {"simd", "nosimd", "+neon", "-neon"}, + {"fp16", "nofp16", "+fullfp16", "-fullfp16"}, + {"profile", "noprofile", "+spe", "-spe"}, + {"ras", "noras", "+ras", "-ras"}}; for (unsigned i = 0; i < array_lengthof(ArchExt); i++) { EXPECT_EQ(StringRef(ArchExt[i][2]), AArch64::getArchExtFeature(ArchExt[i][0])); @@ -517,7 +519,7 @@ "armv8.1-a", "armv8.2a", "armv8.2-a"}; for (unsigned i = 0; i < array_lengthof(Arch); i++) - EXPECT_FALSE(AArch64::getDefaultCPU(Arch[i]).empty()); + EXPECT_FALSE(AArch64::getDefaultCPU(StringRef(Arch[i])).empty()); } TEST(TargetParserTest, AArch64parseArch) { @@ -526,7 +528,7 @@ for (unsigned i = 0; i < array_lengthof(Arch); i++) EXPECT_NE(static_cast(AArch64::ArchKind::AK_INVALID), - AArch64::parseArch(Arch[i])); + AArch64::parseArch(StringRef(Arch[i]))); EXPECT_EQ(static_cast(AArch64::ArchKind::AK_INVALID), AArch64::parseArch("aarch64")); EXPECT_EQ(static_cast(AArch64::ArchKind::AK_INVALID), @@ -534,8 +536,8 @@ } TEST(TargetParserTest, AArch64parseArchExt) { - const char *ArchExt[] = {"none", "crc", "crypto", "fp", - "simd", "fp16", "profile", "ras"}; + StringRef ArchExt[] = {"none", "crc", "crypto", "fp", + "simd", "fp16", "profile", "ras"}; for (unsigned i = 0; i < array_lengthof(ArchExt); i++) EXPECT_NE(AArch64::AEK_INVALID, AArch64::parseArchExt(ArchExt[i])); @@ -548,7 +550,7 @@ "vulcan"}; for (const auto &AArch64CPUName : kAArch64CPUNames) - EXPECT_TRUE(contains(CPU, AArch64CPUName.Name) + EXPECT_TRUE(contains(CPU, AArch64CPUName.Name.data()) ? (static_cast(AArch64::ArchKind::AK_INVALID) != AArch64::parseCPUArch(AArch64CPUName.Name)) : (static_cast(AArch64::ArchKind::AK_INVALID) == Index: llvm/unittests/Support/raw_pwrite_stream_test.cpp =================================================================== --- llvm/unittests/Support/raw_pwrite_stream_test.cpp +++ llvm/unittests/Support/raw_pwrite_stream_test.cpp @@ -58,7 +58,7 @@ // in the parent. const char *ParentPath = getenv("RAW_PWRITE_TEST_FILE"); if (ParentPath) { - Path = ParentPath; + Path = StringRef(ParentPath); ASSERT_NO_ERROR(sys::fs::openFileForRead(Path, FD)); } else { ASSERT_NO_ERROR(sys::fs::createTemporaryFile("foo", "bar", FD, Path)); Index: llvm/utils/FileCheck/FileCheck.cpp =================================================================== --- llvm/utils/FileCheck/FileCheck.cpp +++ llvm/utils/FileCheck/FileCheck.cpp @@ -1309,7 +1309,7 @@ } int main(int argc, char **argv) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); Index: llvm/utils/KillTheDoctor/KillTheDoctor.cpp =================================================================== --- llvm/utils/KillTheDoctor/KillTheDoctor.cpp +++ llvm/utils/KillTheDoctor/KillTheDoctor.cpp @@ -296,7 +296,7 @@ int main(int argc, char **argv) { // Print a stack trace if we signal out. - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. Index: llvm/utils/TableGen/Attributes.cpp =================================================================== --- llvm/utils/TableGen/Attributes.cpp +++ llvm/utils/TableGen/Attributes.cpp @@ -100,7 +100,8 @@ OS << " }\n\n"; OS << " static void set(Function &Fn,\n"; OS << " StringRef Kind, bool Val) {\n"; - OS << " Fn.addFnAttr(Kind, Val ? \"true\" : \"false\");\n"; + OS << " Fn.addFnAttr(Kind, Val ? StringRef(\"true\")\n"; + OS << " : StringRef(\"false\"));\n"; OS << " }\n"; OS << "};\n\n"; Index: llvm/utils/TableGen/IntrinsicEmitter.cpp =================================================================== --- llvm/utils/TableGen/IntrinsicEmitter.cpp +++ llvm/utils/TableGen/IntrinsicEmitter.cpp @@ -686,7 +686,7 @@ void IntrinsicEmitter::EmitIntrinsicToBuiltinMap( const CodeGenIntrinsicTable &Ints, bool IsGCC, raw_ostream &OS) { - StringRef CompilerName = (IsGCC ? "GCC" : "MS"); + StringRef CompilerName(IsGCC ? "GCC" : "MS"); typedef std::map> BIMTy; BIMTy BuiltinMap; StringToOffsetTable Table; @@ -757,7 +757,7 @@ OS << " std::end(" << I->first << "Names),\n"; OS << " BuiltinNameStr);\n"; OS << " if (I != std::end(" << I->first << "Names) &&\n"; - OS << " I->getName() == BuiltinNameStr)\n"; + OS << " StringRef(I->getName()) == BuiltinNameStr)\n"; OS << " return I->IntrinID;\n"; OS << " }\n"; } Index: llvm/utils/TableGen/TableGen.cpp =================================================================== --- llvm/utils/TableGen/TableGen.cpp +++ llvm/utils/TableGen/TableGen.cpp @@ -184,7 +184,7 @@ } int main(int argc, char **argv) { - sys::PrintStackTraceOnErrorSignal(argv[0]); + sys::PrintStackTraceOnErrorSignal(StringRef(argv[0])); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); Index: llvm/utils/not/not.cpp =================================================================== --- llvm/utils/not/not.cpp +++ llvm/utils/not/not.cpp @@ -32,7 +32,7 @@ if (argc == 0) return 1; - auto Program = sys::findProgramByName(argv[0]); + auto Program = sys::findProgramByName(StringRef(argv[0])); if (!Program) { errs() << "Error: Unable to find `" << argv[0] << "' in PATH: " << Program.getError().message() << "\n"; Index: llvm/utils/unittest/UnitTestMain/TestMain.cpp =================================================================== --- llvm/utils/unittest/UnitTestMain/TestMain.cpp +++ llvm/utils/unittest/UnitTestMain/TestMain.cpp @@ -22,7 +22,7 @@ const char *TestMainArgv0; int main(int argc, char **argv) { - llvm::sys::PrintStackTraceOnErrorSignal(argv[0], + llvm::sys::PrintStackTraceOnErrorSignal(llvm::StringRef(argv[0]), true /* Disable crash reporting */); testing::InitGoogleTest(&argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv); Index: polly/lib/Analysis/ScopInfo.cpp =================================================================== --- polly/lib/Analysis/ScopInfo.cpp +++ polly/lib/Analysis/ScopInfo.cpp @@ -3552,7 +3552,7 @@ "BasePtr and BaseName can not be nullptr at the same time."); assert(!(BasePtr && BaseName) && "BaseName is redundant."); auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)] - : ScopArrayNameMap[BaseName]; + : ScopArrayNameMap[StringRef(BaseName)]; if (!SAI) { auto &DL = getFunction().getParent()->getDataLayout(); SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind, Index: polly/lib/CodeGen/BlockGenerators.cpp =================================================================== --- polly/lib/CodeGen/BlockGenerators.cpp +++ polly/lib/CodeGen/BlockGenerators.cpp @@ -241,8 +241,9 @@ NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_"); if (DebugPrinting) - RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer, - ": ", ScalarLoad, "\n"); + RuntimeDebugBuilder::createCPUPrinter(Builder, StringRef("Load from "), + NewPointer, StringRef(": "), + ScalarLoad, StringRef("\n")); return ScalarLoad; } @@ -256,8 +257,9 @@ getLoopForStmt(Stmt)); if (DebugPrinting) - RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer, - ": ", ValueOperand, "\n"); + RuntimeDebugBuilder::createCPUPrinter(Builder, StringRef("Store to "), + NewPointer, StringRef(": "), + ValueOperand, StringRef("\n")); Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment()); } Index: polly/lib/CodeGen/RuntimeDebugBuilder.cpp =================================================================== --- polly/lib/CodeGen/RuntimeDebugBuilder.cpp +++ polly/lib/CodeGen/RuntimeDebugBuilder.cpp @@ -21,7 +21,7 @@ Function *RuntimeDebugBuilder::getVPrintF(PollyIRBuilder &Builder) { Module *M = Builder.GetInsertBlock()->getParent()->getParent(); - const char *Name = "vprintf"; + StringRef Name = "vprintf"; Function *F = M->getFunction(Name); if (!F) { @@ -228,7 +228,7 @@ Function *RuntimeDebugBuilder::getPrintF(PollyIRBuilder &Builder) { Module *M = Builder.GetInsertBlock()->getParent()->getParent(); - const char *Name = "printf"; + StringRef Name = "printf"; Function *F = M->getFunction(Name); if (!F) { @@ -253,7 +253,7 @@ void RuntimeDebugBuilder::createFlush(PollyIRBuilder &Builder) { Module *M = Builder.GetInsertBlock()->getParent()->getParent(); - const char *Name = "fflush"; + StringRef Name = "fflush"; Function *F = M->getFunction(Name); if (!F) {