1 //===- ConcatOutputSection.cpp --------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "ConcatOutputSection.h" 10 #include "Config.h" 11 #include "OutputSegment.h" 12 #include "SymbolTable.h" 13 #include "Symbols.h" 14 #include "SyntheticSections.h" 15 #include "Target.h" 16 #include "lld/Common/ErrorHandler.h" 17 #include "lld/Common/Memory.h" 18 #include "llvm/BinaryFormat/MachO.h" 19 #include "llvm/Support/ScopedPrinter.h" 20 #include "llvm/Support/TimeProfiler.h" 21 22 using namespace llvm; 23 using namespace llvm::MachO; 24 using namespace lld; 25 using namespace lld::macho; 26 27 void ConcatOutputSection::addInput(ConcatInputSection *input) { 28 if (inputs.empty()) { 29 align = input->align; 30 flags = input->getFlags(); 31 } else { 32 align = std::max(align, input->align); 33 finalizeFlags(input); 34 } 35 inputs.push_back(input); 36 input->parent = this; 37 } 38 39 // Branch-range extension can be implemented in two ways, either through ... 40 // 41 // (1) Branch islands: Single branch instructions (also of limited range), 42 // that might be chained in multiple hops to reach the desired 43 // destination. On ARM64, as 16 branch islands are needed to hop between 44 // opposite ends of a 2 GiB program. LD64 uses branch islands exclusively, 45 // even when it needs excessive hops. 46 // 47 // (2) Thunks: Instruction(s) to load the destination address into a scratch 48 // register, followed by a register-indirect branch. Thunks are 49 // constructed to reach any arbitrary address, so need not be 50 // chained. Although thunks need not be chained, a program might need 51 // multiple thunks to the same destination distributed throughout a large 52 // program so that all call sites can have one within range. 53 // 54 // The optimal approach is to mix islands for distinations within two hops, 55 // and use thunks for destinations at greater distance. For now, we only 56 // implement thunks. TODO: Adding support for branch islands! 57 // 58 // Internally -- as expressed in LLD's data structures -- a 59 // branch-range-extension thunk comprises ... 60 // 61 // (1) new Defined privateExtern symbol for the thunk named 62 // <FUNCTION>.thunk.<SEQUENCE>, which references ... 63 // (2) new InputSection, which contains ... 64 // (3.1) new data for the instructions to load & branch to the far address + 65 // (3.2) new Relocs on instructions to load the far address, which reference ... 66 // (4.1) existing Defined extern symbol for the real function in __text, or 67 // (4.2) existing DylibSymbol for the real function in a dylib 68 // 69 // Nearly-optimal thunk-placement algorithm features: 70 // 71 // * Single pass: O(n) on the number of call sites. 72 // 73 // * Accounts for the exact space overhead of thunks - no heuristics 74 // 75 // * Exploits the full range of call instructions - forward & backward 76 // 77 // Data: 78 // 79 // * DenseMap<Symbol *, ThunkInfo> thunkMap: Maps the function symbol 80 // to its thunk bookkeeper. 81 // 82 // * struct ThunkInfo (bookkeeper): Call instructions have limited range, and 83 // distant call sites might be unable to reach the same thunk, so multiple 84 // thunks are necessary to serve all call sites in a very large program. A 85 // thunkInfo stores state for all thunks associated with a particular 86 // function: (a) thunk symbol, (b) input section containing stub code, and 87 // (c) sequence number for the active thunk incarnation. When an old thunk 88 // goes out of range, we increment the sequence number and create a new 89 // thunk named <FUNCTION>.thunk.<SEQUENCE>. 90 // 91 // * A thunk incarnation comprises (a) private-extern Defined symbol pointing 92 // to (b) an InputSection holding machine instructions (similar to a MachO 93 // stub), and (c) Reloc(s) that reference the real function for fixing-up 94 // the stub code. 95 // 96 // * std::vector<InputSection *> MergedInputSection::thunks: A vector parallel 97 // to the inputs vector. We store new thunks via cheap vector append, rather 98 // than costly insertion into the inputs vector. 99 // 100 // Control Flow: 101 // 102 // * During address assignment, MergedInputSection::finalize() examines call 103 // sites by ascending address and creates thunks. When a function is beyond 104 // the range of a call site, we need a thunk. Place it at the largest 105 // available forward address from the call site. Call sites increase 106 // monotonically and thunks are always placed as far forward as possible; 107 // thus, we place thunks at monotonically increasing addresses. Once a thunk 108 // is placed, it and all previous input-section addresses are final. 109 // 110 // * MergedInputSection::finalize() and MergedInputSection::writeTo() merge 111 // the inputs and thunks vectors (both ordered by ascending address), which 112 // is simple and cheap. 113 114 DenseMap<Symbol *, ThunkInfo> lld::macho::thunkMap; 115 116 // Determine whether we need thunks, which depends on the target arch -- RISC 117 // (i.e., ARM) generally does because it has limited-range branch/call 118 // instructions, whereas CISC (i.e., x86) generally doesn't. RISC only needs 119 // thunks for programs so large that branch source & destination addresses 120 // might differ more than the range of branch instruction(s). 121 bool ConcatOutputSection::needsThunks() const { 122 if (!target->usesThunks()) 123 return false; 124 uint64_t isecAddr = addr; 125 for (InputSection *isec : inputs) 126 isecAddr = alignTo(isecAddr, isec->align) + isec->getSize(); 127 if (isecAddr - addr + in.stubs->getSize() <= target->branchRange) 128 return false; 129 // Yes, this program is large enough to need thunks. 130 for (InputSection *isec : inputs) { 131 for (Reloc &r : isec->relocs) { 132 if (!target->hasAttr(r.type, RelocAttrBits::BRANCH)) 133 continue; 134 auto *sym = r.referent.get<Symbol *>(); 135 // Pre-populate the thunkMap and memoize call site counts for every 136 // InputSection and ThunkInfo. We do this for the benefit of 137 // ConcatOutputSection::estimateStubsInRangeVA() 138 ThunkInfo &thunkInfo = thunkMap[sym]; 139 // Knowing ThunkInfo call site count will help us know whether or not we 140 // might need to create more for this referent at the time we are 141 // estimating distance to __stubs in . 142 ++thunkInfo.callSiteCount; 143 // Knowing InputSection call site count will help us avoid work on those 144 // that have no BRANCH relocs. 145 ++isec->callSiteCount; 146 } 147 } 148 return true; 149 } 150 151 // Since __stubs is placed after __text, we must estimate the address 152 // beyond which stubs are within range of a simple forward branch. 153 uint64_t ConcatOutputSection::estimateStubsInRangeVA(size_t callIdx) const { 154 uint64_t branchRange = target->branchRange; 155 size_t endIdx = inputs.size(); 156 ConcatInputSection *isec = inputs[callIdx]; 157 uint64_t isecVA = isec->getVA(); 158 // Tally the non-stub functions which still have call sites 159 // remaining to process, which yields the maximum number 160 // of thunks we might yet place. 161 size_t maxPotentialThunks = 0; 162 for (auto &tp : thunkMap) { 163 ThunkInfo &ti = tp.second; 164 maxPotentialThunks += 165 !tp.first->isInStubs() && ti.callSitesUsed < ti.callSiteCount; 166 } 167 // Tally the total size of input sections remaining to process. 168 uint64_t isecEnd = isec->getVA(); 169 for (size_t i = callIdx; i < endIdx; i++) { 170 InputSection *isec = inputs[i]; 171 isecEnd = alignTo(isecEnd, isec->align) + isec->getSize(); 172 } 173 // Estimate the address after which call sites can safely call stubs 174 // directly rather than through intermediary thunks. 175 uint64_t stubsInRangeVA = isecEnd + maxPotentialThunks * target->thunkSize + 176 in.stubs->getSize() - branchRange; 177 log("thunks = " + std::to_string(thunkMap.size()) + 178 ", potential = " + std::to_string(maxPotentialThunks) + 179 ", stubs = " + std::to_string(in.stubs->getSize()) + ", isecVA = " + 180 to_hexString(isecVA) + ", threshold = " + to_hexString(stubsInRangeVA) + 181 ", isecEnd = " + to_hexString(isecEnd) + 182 ", tail = " + to_hexString(isecEnd - isecVA) + 183 ", slop = " + to_hexString(branchRange - (isecEnd - isecVA))); 184 return stubsInRangeVA; 185 } 186 187 void ConcatOutputSection::finalize() { 188 uint64_t isecAddr = addr; 189 uint64_t isecFileOff = fileOff; 190 auto finalizeOne = [&](ConcatInputSection *isec) { 191 isecAddr = alignTo(isecAddr, isec->align); 192 isecFileOff = alignTo(isecFileOff, isec->align); 193 isec->outSecOff = isecAddr - addr; 194 isec->isFinal = true; 195 isecAddr += isec->getSize(); 196 isecFileOff += isec->getFileSize(); 197 }; 198 199 if (!needsThunks()) { 200 for (ConcatInputSection *isec : inputs) 201 finalizeOne(isec); 202 size = isecAddr - addr; 203 fileSize = isecFileOff - fileOff; 204 return; 205 } 206 207 uint64_t branchRange = target->branchRange; 208 uint64_t stubsInRangeVA = TargetInfo::outOfRangeVA; 209 size_t thunkSize = target->thunkSize; 210 size_t relocCount = 0; 211 size_t callSiteCount = 0; 212 size_t thunkCallCount = 0; 213 size_t thunkCount = 0; 214 215 // inputs[finalIdx] is for finalization (address-assignment) 216 size_t finalIdx = 0; 217 // Kick-off by ensuring that the first input section has an address 218 for (size_t callIdx = 0, endIdx = inputs.size(); callIdx < endIdx; 219 ++callIdx) { 220 if (finalIdx == callIdx) 221 finalizeOne(inputs[finalIdx++]); 222 ConcatInputSection *isec = inputs[callIdx]; 223 assert(isec->isFinal); 224 uint64_t isecVA = isec->getVA(); 225 // Assign addresses up-to the forward branch-range limit 226 while (finalIdx < endIdx && 227 isecAddr + inputs[finalIdx]->getSize() < isecVA + branchRange) 228 finalizeOne(inputs[finalIdx++]); 229 if (isec->callSiteCount == 0) 230 continue; 231 if (finalIdx == endIdx && stubsInRangeVA == TargetInfo::outOfRangeVA) { 232 // When we have finalized all input sections, __stubs (destined 233 // to follow __text) comes within range of forward branches and 234 // we can estimate the threshold address after which we can 235 // reach any stub with a forward branch. Note that although it 236 // sits in the middle of a loop, this code executes only once. 237 // It is in the loop because we need to call it at the proper 238 // time: the earliest call site from which the end of __text 239 // (and start of __stubs) comes within range of a forward branch. 240 stubsInRangeVA = estimateStubsInRangeVA(callIdx); 241 } 242 // Process relocs by ascending address, i.e., ascending offset within isec 243 std::vector<Reloc> &relocs = isec->relocs; 244 // FIXME: This property does not hold for object files produced by ld64's 245 // `-r` mode. 246 assert(is_sorted(relocs, 247 [](Reloc &a, Reloc &b) { return a.offset > b.offset; })); 248 for (Reloc &r : reverse(relocs)) { 249 ++relocCount; 250 if (!target->hasAttr(r.type, RelocAttrBits::BRANCH)) 251 continue; 252 ++callSiteCount; 253 // Calculate branch reachability boundaries 254 uint64_t callVA = isecVA + r.offset; 255 uint64_t lowVA = branchRange < callVA ? callVA - branchRange : 0; 256 uint64_t highVA = callVA + branchRange; 257 // Calculate our call referent address 258 auto *funcSym = r.referent.get<Symbol *>(); 259 ThunkInfo &thunkInfo = thunkMap[funcSym]; 260 // The referent is not reachable, so we need to use a thunk ... 261 if (funcSym->isInStubs() && callVA >= stubsInRangeVA) { 262 // ... Oh, wait! We are close enough to the end that __stubs 263 // are now within range of a simple forward branch. 264 continue; 265 } 266 uint64_t funcVA = funcSym->resolveBranchVA(); 267 ++thunkInfo.callSitesUsed; 268 if (lowVA < funcVA && funcVA < highVA) { 269 // The referent is reachable with a simple call instruction. 270 continue; 271 } 272 ++thunkInfo.thunkCallCount; 273 ++thunkCallCount; 274 // If an existing thunk is reachable, use it ... 275 if (thunkInfo.sym) { 276 uint64_t thunkVA = thunkInfo.isec->getVA(); 277 if (lowVA < thunkVA && thunkVA < highVA) { 278 r.referent = thunkInfo.sym; 279 continue; 280 } 281 } 282 // ... otherwise, create a new thunk 283 if (isecAddr > highVA) { 284 // When there is small-to-no margin between highVA and 285 // isecAddr and the distance between subsequent call sites is 286 // smaller than thunkSize, then a new thunk can go out of 287 // range. Fix by unfinalizing inputs[finalIdx] to reduce the 288 // distance between callVA and highVA, then shift some thunks 289 // to occupy address-space formerly occupied by the 290 // unfinalized inputs[finalIdx]. 291 fatal(Twine(__FUNCTION__) + ": FIXME: thunk range overrun"); 292 } 293 thunkInfo.isec = 294 make<ConcatInputSection>(isec->getSegName(), isec->getName()); 295 thunkInfo.isec->parent = this; 296 StringRef thunkName = saver.save(funcSym->getName() + ".thunk." + 297 std::to_string(thunkInfo.sequence++)); 298 r.referent = thunkInfo.sym = symtab->addDefined( 299 thunkName, /*file=*/nullptr, thunkInfo.isec, /*value=*/0, 300 /*size=*/thunkSize, /*isWeakDef=*/false, /*isPrivateExtern=*/true, 301 /*isThumb=*/false, /*isReferencedDynamically=*/false, 302 /*noDeadStrip=*/false); 303 target->populateThunk(thunkInfo.isec, funcSym); 304 finalizeOne(thunkInfo.isec); 305 thunks.push_back(thunkInfo.isec); 306 ++thunkCount; 307 } 308 } 309 size = isecAddr - addr; 310 fileSize = isecFileOff - fileOff; 311 312 log("thunks for " + parent->name + "," + name + 313 ": funcs = " + std::to_string(thunkMap.size()) + 314 ", relocs = " + std::to_string(relocCount) + 315 ", all calls = " + std::to_string(callSiteCount) + 316 ", thunk calls = " + std::to_string(thunkCallCount) + 317 ", thunks = " + std::to_string(thunkCount)); 318 } 319 320 void ConcatOutputSection::writeTo(uint8_t *buf) const { 321 // Merge input sections from thunk & ordinary vectors 322 size_t i = 0, ie = inputs.size(); 323 size_t t = 0, te = thunks.size(); 324 while (i < ie || t < te) { 325 while (i < ie && (t == te || inputs[i]->getSize() == 0 || 326 inputs[i]->outSecOff < thunks[t]->outSecOff)) { 327 inputs[i]->writeTo(buf + inputs[i]->outSecOff); 328 ++i; 329 } 330 while (t < te && (i == ie || thunks[t]->outSecOff < inputs[i]->outSecOff)) { 331 thunks[t]->writeTo(buf + thunks[t]->outSecOff); 332 ++t; 333 } 334 } 335 } 336 337 void ConcatOutputSection::finalizeFlags(InputSection *input) { 338 switch (sectionType(input->getFlags())) { 339 default /*type-unspec'ed*/: 340 // FIXME: Add additional logics here when supporting emitting obj files. 341 break; 342 case S_4BYTE_LITERALS: 343 case S_8BYTE_LITERALS: 344 case S_16BYTE_LITERALS: 345 case S_CSTRING_LITERALS: 346 case S_ZEROFILL: 347 case S_LAZY_SYMBOL_POINTERS: 348 case S_MOD_TERM_FUNC_POINTERS: 349 case S_THREAD_LOCAL_REGULAR: 350 case S_THREAD_LOCAL_ZEROFILL: 351 case S_THREAD_LOCAL_VARIABLES: 352 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS: 353 case S_THREAD_LOCAL_VARIABLE_POINTERS: 354 case S_NON_LAZY_SYMBOL_POINTERS: 355 case S_SYMBOL_STUBS: 356 flags |= input->getFlags(); 357 break; 358 } 359 } 360