[lld-macho][NFC] when reasonable, replace auto keyword with type names

lld policy discourages `auto`. Replace it with a type name whenever reasonable. Retain `auto` to avoid ...
* redundancy, as for decls such as `auto *t = mumble_cast<TYPE *>` or similar that specifies the result type on the RHS
* verbosity, as for iterators
* gratuitous suffering, as for lambdas

Along the way, add `const` when appropriate.

Note: a future diff will ...
* add more `const` qualifiers
* remove `opt::` when we are already `using llvm::opt`

Differential Revision: https://reviews.llvm.org/D98313
This commit is contained in:
Greg McGary 2021-03-09 20:15:29 -08:00
parent ee35784a90
commit fdc0c21973
8 changed files with 42 additions and 40 deletions

View File

@ -164,8 +164,8 @@ getSearchPaths(unsigned optionCode, opt::InputArgList &args,
if (args.hasArg(OPT_Z)) if (args.hasArg(OPT_Z))
return paths; return paths;
for (auto const &path : systemPaths) { for (const StringRef &path : systemPaths) {
for (auto root : roots) { for (const StringRef &root : roots) {
SmallString<261> buffer(root); SmallString<261> buffer(root);
path::append(buffer, path); path::append(buffer, path);
if (fs::is_directory(buffer)) if (fs::is_directory(buffer))
@ -252,7 +252,7 @@ static InputFile *addFile(StringRef path, bool forceLoadArchive,
MemoryBufferRef mbref = *buffer; MemoryBufferRef mbref = *buffer;
InputFile *newFile = nullptr; InputFile *newFile = nullptr;
auto magic = identify_magic(mbref.getBuffer()); file_magic magic = identify_magic(mbref.getBuffer());
switch (magic) { switch (magic) {
case file_magic::archive: { case file_magic::archive: {
std::unique_ptr<object::Archive> file = CHECK( std::unique_ptr<object::Archive> file = CHECK(
@ -368,10 +368,10 @@ void macho::parseLCLinkerOption(InputFile* f, unsigned argc, StringRef data) {
opt::InputArgList args = table.ParseArgs(argv, missingIndex, missingCount); opt::InputArgList args = table.ParseArgs(argv, missingIndex, missingCount);
if (missingCount) if (missingCount)
fatal(Twine(args.getArgString(missingIndex)) + ": missing argument"); fatal(Twine(args.getArgString(missingIndex)) + ": missing argument");
for (auto *arg : args.filtered(OPT_UNKNOWN)) for (const Arg *arg : args.filtered(OPT_UNKNOWN))
error("unknown argument: " + arg->getAsString(args)); error("unknown argument: " + arg->getAsString(args));
for (auto *arg : args) { for (const Arg *arg : args) {
switch (arg->getOption().getID()) { switch (arg->getOption().getID()) {
case OPT_l: case OPT_l:
addLibrary(arg->getValue(), false); addLibrary(arg->getValue(), false);
@ -493,7 +493,7 @@ static void initLLVM() {
} }
static void compileBitcodeFiles() { static void compileBitcodeFiles() {
auto lto = make<BitcodeCompiler>(); auto *lto = make<BitcodeCompiler>();
for (InputFile *file : inputFiles) for (InputFile *file : inputFiles)
if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file)) if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file))
lto->add(*bitcodeFile); lto->add(*bitcodeFile);
@ -663,7 +663,7 @@ static void warnIfUnimplementedOption(const opt::Option &opt) {
} }
static const char *getReproduceOption(opt::InputArgList &args) { static const char *getReproduceOption(opt::InputArgList &args) {
if (auto *arg = args.getLastArg(OPT_reproduce)) if (const Arg *arg = args.getLastArg(OPT_reproduce))
return arg->getValue(); return arg->getValue();
return getenv("LLD_REPRODUCE"); return getenv("LLD_REPRODUCE");
} }
@ -752,9 +752,9 @@ static void handleSymbolPatterns(opt::InputArgList &args,
SymbolPatterns &symbolPatterns, SymbolPatterns &symbolPatterns,
unsigned singleOptionCode, unsigned singleOptionCode,
unsigned listFileOptionCode) { unsigned listFileOptionCode) {
for (opt::Arg *arg : args.filtered(singleOptionCode)) for (const Arg *arg : args.filtered(singleOptionCode))
symbolPatterns.insert(arg->getValue()); symbolPatterns.insert(arg->getValue());
for (opt::Arg *arg : args.filtered(listFileOptionCode)) { for (const Arg *arg : args.filtered(listFileOptionCode)) {
StringRef path = arg->getValue(); StringRef path = arg->getValue();
Optional<MemoryBufferRef> buffer = readFile(path); Optional<MemoryBufferRef> buffer = readFile(path);
if (!buffer) { if (!buffer) {
@ -819,12 +819,12 @@ bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly,
config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"), config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"),
/*file=*/nullptr, /*file=*/nullptr,
/*isWeakRef=*/false); /*isWeakRef=*/false);
for (auto *arg : args.filtered(OPT_u)) { for (const Arg *arg : args.filtered(OPT_u)) {
config->explicitUndefineds.push_back(symtab->addUndefined( config->explicitUndefineds.push_back(symtab->addUndefined(
arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false)); arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false));
} }
for (auto *arg : args.filtered(OPT_U)) for (const Arg *arg : args.filtered(OPT_U))
symtab->addDynamicLookup(arg->getValue()); symtab->addDynamicLookup(arg->getValue());
config->outputFile = args.getLastArgValue(OPT_o, "a.out"); config->outputFile = args.getLastArgValue(OPT_o, "a.out");
@ -884,12 +884,12 @@ bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly,
error("invalid name for segment or section: " + s); error("invalid name for segment or section: " + s);
return s; return s;
}; };
for (opt::Arg *arg : args.filtered(OPT_rename_section)) { for (const Arg *arg : args.filtered(OPT_rename_section)) {
config->sectionRenameMap[{validName(arg->getValue(0)), config->sectionRenameMap[{validName(arg->getValue(0)),
validName(arg->getValue(1))}] = { validName(arg->getValue(1))}] = {
validName(arg->getValue(2)), validName(arg->getValue(3))}; validName(arg->getValue(2)), validName(arg->getValue(3))};
} }
for (opt::Arg *arg : args.filtered(OPT_rename_segment)) { for (const Arg *arg : args.filtered(OPT_rename_segment)) {
config->segmentRenameMap[validName(arg->getValue(0))] = config->segmentRenameMap[validName(arg->getValue(0))] =
validName(arg->getValue(1)); validName(arg->getValue(1));
} }
@ -926,8 +926,8 @@ bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly,
// This loop should be reserved for options whose exact ordering matters. // This loop should be reserved for options whose exact ordering matters.
// Other options should be handled via filtered() and/or getLastArg(). // Other options should be handled via filtered() and/or getLastArg().
for (const auto &arg : args) { for (const Arg *arg : args) {
const auto &opt = arg->getOption(); const Option &opt = arg->getOption();
warnIfDeprecatedOption(opt); warnIfDeprecatedOption(opt);
warnIfUnimplementedOption(opt); warnIfUnimplementedOption(opt);
@ -964,7 +964,7 @@ bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly,
// Now that all dylibs have been loaded, search for those that should be // Now that all dylibs have been loaded, search for those that should be
// re-exported. // re-exported.
for (opt::Arg *arg : args.filtered(OPT_sub_library, OPT_sub_umbrella)) { for (const Arg *arg : args.filtered(OPT_sub_library, OPT_sub_umbrella)) {
config->hasReexports = true; config->hasReexports = true;
StringRef searchName = arg->getValue(); StringRef searchName = arg->getValue();
std::vector<StringRef> extensions; std::vector<StringRef> extensions;
@ -978,11 +978,11 @@ bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly,
} }
// Parse LTO options. // Parse LTO options.
if (auto *arg = args.getLastArg(OPT_mcpu)) if (const Arg *arg = args.getLastArg(OPT_mcpu))
parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())), parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
arg->getSpelling()); arg->getSpelling());
for (auto *arg : args.filtered(OPT_mllvm)) for (const Arg *arg : args.filtered(OPT_mllvm))
parseClangOption(arg->getValue(), arg->getSpelling()); parseClangOption(arg->getValue(), arg->getSpelling());
compileBitcodeFiles(); compileBitcodeFiles();
@ -998,7 +998,7 @@ bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly,
} }
// FIXME: This prints symbols that are undefined both in input files and // FIXME: This prints symbols that are undefined both in input files and
// via -u flag twice. // via -u flag twice.
for (const auto *undefined : config->explicitUndefineds) { for (const Symbol *undefined : config->explicitUndefineds) {
if (isa<Undefined>(undefined)) { if (isa<Undefined>(undefined)) {
error("undefined symbol: " + toString(*undefined) + error("undefined symbol: " + toString(*undefined) +
"\n>>> referenced by flag -u " + toString(*undefined)); "\n>>> referenced by flag -u " + toString(*undefined));
@ -1009,7 +1009,7 @@ bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly,
createSyntheticSections(); createSyntheticSections();
symtab->addDSOHandle(in.header); symtab->addDSOHandle(in.header);
for (opt::Arg *arg : args.filtered(OPT_sectcreate)) { for (const Arg *arg : args.filtered(OPT_sectcreate)) {
StringRef segName = arg->getValue(0); StringRef segName = arg->getValue(0);
StringRef sectName = arg->getValue(1); StringRef sectName = arg->getValue(1);
StringRef fileName = arg->getValue(2); StringRef fileName = arg->getValue(2);
@ -1021,7 +1021,7 @@ bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly,
// Initialize InputSections. // Initialize InputSections.
for (InputFile *file : inputFiles) { for (InputFile *file : inputFiles) {
for (SubsectionMap &map : file->subsections) { for (SubsectionMap &map : file->subsections) {
for (auto &p : map) { for (const auto &p : map) {
InputSection *isec = p.second; InputSection *isec = p.second;
inputSections.push_back(isec); inputSections.push_back(isec);
} }

View File

@ -52,8 +52,9 @@ MachOOptTable::MachOOptTable() : OptTable(optInfo) {}
// Set color diagnostics according to --color-diagnostics={auto,always,never} // Set color diagnostics according to --color-diagnostics={auto,always,never}
// or --no-color-diagnostics flags. // or --no-color-diagnostics flags.
static void handleColorDiagnostics(opt::InputArgList &args) { static void handleColorDiagnostics(opt::InputArgList &args) {
auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq, const Arg *arg =
OPT_no_color_diagnostics); args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
OPT_no_color_diagnostics);
if (!arg) if (!arg)
return; return;
if (arg->getOption().getID() == OPT_color_diagnostics) { if (arg->getOption().getID() == OPT_color_diagnostics) {
@ -121,7 +122,7 @@ std::string macho::createResponseFile(const opt::InputArgList &args) {
raw_svector_ostream os(data); raw_svector_ostream os(data);
// Copy the command line to the output while rewriting paths. // Copy the command line to the output while rewriting paths.
for (auto *arg : args) { for (const Arg *arg : args) {
switch (arg->getOption().getID()) { switch (arg->getOption().getID()) {
case OPT_reproduce: case OPT_reproduce:
break; break;

View File

@ -99,8 +99,8 @@ int InputFile::idCount = 0;
// Open a given file path and return it as a memory-mapped file. // Open a given file path and return it as a memory-mapped file.
Optional<MemoryBufferRef> macho::readFile(StringRef path) { Optional<MemoryBufferRef> macho::readFile(StringRef path) {
// Open a file. // Open a file.
auto mbOrErr = MemoryBuffer::getFile(path); ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
if (auto ec = mbOrErr.getError()) { if (std::error_code ec = mbOrErr.getError()) {
error("cannot open " + path + ": " + ec.message()); error("cannot open " + path + ": " + ec.message());
return None; return None;
} }
@ -749,7 +749,7 @@ DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
}; };
// TODO(compnerd) filter out symbols based on the target platform // TODO(compnerd) filter out symbols based on the target platform
// TODO: handle weak defs, thread locals // TODO: handle weak defs, thread locals
for (const auto symbol : interface.symbols()) { for (const auto *symbol : interface.symbols()) {
if (!symbol->getArchitectures().has(config->target.Arch)) if (!symbol->getArchitectures().has(config->target.Arch))
continue; continue;
@ -776,7 +776,7 @@ DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
interface.getParent() == nullptr ? &interface : interface.getParent(); interface.getParent() == nullptr ? &interface : interface.getParent();
for (InterfaceFileRef intfRef : interface.reexportedLibraries()) { for (InterfaceFileRef intfRef : interface.reexportedLibraries()) {
auto targets = intfRef.targets(); InterfaceFile::const_target_range targets = intfRef.targets();
if (is_contained(targets, config->target)) if (is_contained(targets, config->target))
loadReexport(intfRef.getInstallName(), exportingFile, topLevel); loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
} }

View File

@ -58,14 +58,15 @@ void InputSection::writeTo(uint8_t *buf) {
memcpy(buf, data.data(), data.size()); memcpy(buf, data.data(), data.size());
for (size_t i = 0; i < relocs.size(); i++) { for (size_t i = 0; i < relocs.size(); i++) {
auto *fromSym = target->hasAttr(relocs[i].type, RelocAttrBits::SUBTRAHEND) const Symbol *fromSym =
? relocs[i++].referent.get<Symbol *>() target->hasAttr(relocs[i].type, RelocAttrBits::SUBTRAHEND)
: nullptr; ? relocs[i++].referent.get<Symbol *>()
: nullptr;
const Reloc &r = relocs[i]; const Reloc &r = relocs[i];
uint8_t *loc = buf + r.offset; uint8_t *loc = buf + r.offset;
uint64_t referentVA = 0; uint64_t referentVA = 0;
if (fromSym) { if (fromSym) {
auto *toSym = r.referent.get<Symbol *>(); const Symbol *toSym = r.referent.get<Symbol *>();
referentVA = toSym->getVA() - fromSym->getVA(); referentVA = toSym->getVA() - fromSym->getVA();
} else if (auto *referentSym = r.referent.dyn_cast<Symbol *>()) { } else if (auto *referentSym = r.referent.dyn_cast<Symbol *>()) {
if (target->hasAttr(r.type, RelocAttrBits::LOAD) && if (target->hasAttr(r.type, RelocAttrBits::LOAD) &&

View File

@ -40,7 +40,7 @@ static lto::Config createConfig() {
} }
BitcodeCompiler::BitcodeCompiler() { BitcodeCompiler::BitcodeCompiler() {
auto backend = lto::ThinBackend backend =
lto::createInProcessThinBackend(heavyweight_hardware_concurrency()); lto::createInProcessThinBackend(heavyweight_hardware_concurrency());
ltoObj = std::make_unique<lto::LTO>(createConfig(), backend); ltoObj = std::make_unique<lto::LTO>(createConfig(), backend);
} }

View File

@ -79,7 +79,7 @@ Symbol *SymbolTable::addUndefined(StringRef name, InputFile *file,
bool wasInserted; bool wasInserted;
std::tie(s, wasInserted) = insert(name); std::tie(s, wasInserted) = insert(name);
auto refState = isWeakRef ? RefState::Weak : RefState::Strong; RefState refState = isWeakRef ? RefState::Weak : RefState::Strong;
if (wasInserted) if (wasInserted)
replaceSymbol<Undefined>(s, name, file, refState); replaceSymbol<Undefined>(s, name, file, refState);
@ -119,7 +119,7 @@ Symbol *SymbolTable::addDylib(StringRef name, DylibFile *file, bool isWeakDef,
bool wasInserted; bool wasInserted;
std::tie(s, wasInserted) = insert(name); std::tie(s, wasInserted) = insert(name);
auto refState = RefState::Unreferenced; RefState refState = RefState::Unreferenced;
if (!wasInserted) { if (!wasInserted) {
if (auto *defined = dyn_cast<Defined>(s)) { if (auto *defined = dyn_cast<Defined>(s)) {
if (isWeakDef && !defined->isWeakDef()) if (isWeakDef && !defined->isWeakDef())

View File

@ -372,11 +372,11 @@ void WeakBindingSection::finalizeContents() {
return a.target.getVA() < b.target.getVA(); return a.target.getVA() < b.target.getVA();
}); });
for (const WeakBindingEntry &b : bindings) { for (const WeakBindingEntry &b : bindings) {
if (auto *isec = b.target.section.dyn_cast<const InputSection *>()) { if (const auto *isec = b.target.section.dyn_cast<const InputSection *>()) {
encodeBinding(b.symbol, isec->parent, isec->outSecOff + b.target.offset, encodeBinding(b.symbol, isec->parent, isec->outSecOff + b.target.offset,
b.addend, /*isWeakBinding=*/true, lastBinding, os); b.addend, /*isWeakBinding=*/true, lastBinding, os);
} else { } else {
auto *osec = b.target.section.get<const OutputSection *>(); const auto *osec = b.target.section.get<const OutputSection *>();
encodeBinding(b.symbol, osec, b.target.offset, b.addend, encodeBinding(b.symbol, osec, b.target.offset, b.addend,
/*isWeakBinding=*/true, lastBinding, os); /*isWeakBinding=*/true, lastBinding, os);
} }

View File

@ -280,7 +280,7 @@ void UnwindInfoSection::finalize() {
// Count frequencies of the folded encodings // Count frequencies of the folded encodings
EncodingMap encodingFrequencies; EncodingMap encodingFrequencies;
for (auto cuPtrEntry : cuPtrVector) for (const CompactUnwindEntry64 *cuPtrEntry : cuPtrVector)
encodingFrequencies[cuPtrEntry->encoding]++; encodingFrequencies[cuPtrEntry->encoding]++;
// Make a vector of encodings, sorted by descending frequency // Make a vector of encodings, sorted by descending frequency
@ -316,7 +316,7 @@ void UnwindInfoSection::finalize() {
// If more entries fit in the regular format, we use that. // If more entries fit in the regular format, we use that.
for (size_t i = 0; i < cuPtrVector.size();) { for (size_t i = 0; i < cuPtrVector.size();) {
secondLevelPages.emplace_back(); secondLevelPages.emplace_back();
auto &page = secondLevelPages.back(); UnwindInfoSection::SecondLevelPage &page = secondLevelPages.back();
page.entryIndex = i; page.entryIndex = i;
uintptr_t functionAddressMax = uintptr_t functionAddressMax =
cuPtrVector[i]->functionAddress + COMPRESSED_ENTRY_FUNC_OFFSET_MASK; cuPtrVector[i]->functionAddress + COMPRESSED_ENTRY_FUNC_OFFSET_MASK;
@ -326,7 +326,7 @@ void UnwindInfoSection::finalize() {
sizeof(unwind_info_compressed_second_level_page_header) / sizeof(unwind_info_compressed_second_level_page_header) /
sizeof(uint32_t); sizeof(uint32_t);
while (wordsRemaining >= 1 && i < cuPtrVector.size()) { while (wordsRemaining >= 1 && i < cuPtrVector.size()) {
const auto *cuPtr = cuPtrVector[i]; const CompactUnwindEntry64 *cuPtr = cuPtrVector[i];
if (cuPtr->functionAddress >= functionAddressMax) { if (cuPtr->functionAddress >= functionAddressMax) {
break; break;
} else if (commonEncodingIndexes.count(cuPtr->encoding) || } else if (commonEncodingIndexes.count(cuPtr->encoding) ||