blob: ed9ef4f0e344c59dc11998c6a688c2ae5b442c17 [file] [log] [blame]
Rui Ueyama00762152015-02-05 20:05:33 +00001//===-- ReaderWriter/MachO/LayoutPass.cpp - Layout atoms ------------------===//
Shankar Easwaran34ab70f2013-02-07 20:16:12 +00002//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Shankar Easwaran34ab70f2013-02-07 20:16:12 +00009
Rui Ueyama00762152015-02-05 20:05:33 +000010#include "LayoutPass.h"
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +000011#include "lld/Core/Instrumentation.h"
Rui Ueyama87d10ef2015-01-26 20:18:37 +000012#include "lld/Core/Parallel.h"
Rui Ueyama00762152015-02-05 20:05:33 +000013#include "lld/Core/PassManager.h"
14#include "lld/ReaderWriter/MachOLinkingContext.h"
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +000015#include "llvm/ADT/Twine.h"
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000016#include "llvm/Support/Debug.h"
Shankar Easwaran2b67fca2014-10-18 05:33:55 +000017#include <algorithm>
18#include <set>
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000019
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000020using namespace lld;
21
Chandler Carruth9afe32d2014-04-22 03:21:31 +000022#define DEBUG_TYPE "LayoutPass"
23
Rui Ueyama00762152015-02-05 20:05:33 +000024namespace lld {
25namespace mach_o {
26
Rui Ueyama5af46222013-12-08 03:24:09 +000027static bool compareAtoms(const LayoutPass::SortKey &,
Nick Kledzik82d24bc2014-11-07 21:01:21 +000028 const LayoutPass::SortKey &,
29 LayoutPass::SortOverride customSorter=nullptr);
Rui Ueyama5af46222013-12-08 03:24:09 +000030
Rui Ueyama2994f6f2013-12-08 03:37:58 +000031#ifndef NDEBUG
Rui Ueyama6a607b62013-10-18 02:56:31 +000032// Return "reason (leftval, rightval)"
Rui Ueyama5af46222013-12-08 03:24:09 +000033static std::string formatReason(StringRef reason, int leftVal, int rightVal) {
Rui Ueyama2ea86392014-09-18 23:21:39 +000034 return (Twine(reason) + " (" + Twine(leftVal) + ", " + Twine(rightVal) + ")")
35 .str();
Rui Ueyama6a607b62013-10-18 02:56:31 +000036}
Rui Ueyama46bf8282013-10-19 03:18:18 +000037
38// Less-than relationship of two atoms must be transitive, which is, if a < b
39// and b < c, a < c must be true. This function checks the transitivity by
40// checking the sort results.
Rui Ueyama5af46222013-12-08 03:24:09 +000041static void checkTransitivity(std::vector<LayoutPass::SortKey> &vec) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000042 for (auto i = vec.begin(), e = vec.end(); (i + 1) != e; ++i) {
43 for (auto j = i + 1; j != e; ++j) {
44 assert(compareAtoms(*i, *j));
45 assert(!compareAtoms(*j, *i));
Rui Ueyama46bf8282013-10-19 03:18:18 +000046 }
47 }
Rui Ueyama6a607b62013-10-18 02:56:31 +000048}
Rui Ueyamaa930d122013-12-09 00:37:19 +000049
50// Helper functions to check follow-on graph.
51typedef llvm::DenseMap<const DefinedAtom *, const DefinedAtom *> AtomToAtomT;
52
53static std::string atomToDebugString(const Atom *atom) {
54 const DefinedAtom *definedAtom = dyn_cast<DefinedAtom>(atom);
55 std::string str;
56 llvm::raw_string_ostream s(str);
57 if (definedAtom->name().empty())
58 s << "<anonymous " << definedAtom << ">";
59 else
60 s << definedAtom->name();
61 s << " in ";
62 if (definedAtom->customSectionName().empty())
63 s << "<anonymous>";
64 else
65 s << definedAtom->customSectionName();
66 s.flush();
67 return str;
68}
69
Nico Rieckb9d84f42014-02-24 21:14:37 +000070static void showCycleDetectedError(const Registry &registry,
71 AtomToAtomT &followOnNexts,
Rui Ueyamaa930d122013-12-09 00:37:19 +000072 const DefinedAtom *atom) {
73 const DefinedAtom *start = atom;
74 llvm::dbgs() << "There's a cycle in a follow-on chain!\n";
75 do {
76 llvm::dbgs() << " " << atomToDebugString(atom) << "\n";
77 for (const Reference *ref : *atom) {
Nico Rieckb9d84f42014-02-24 21:14:37 +000078 StringRef kindValStr;
79 if (!registry.referenceKindToString(ref->kindNamespace(), ref->kindArch(),
80 ref->kindValue(), kindValStr)) {
81 kindValStr = "<unknown>";
82 }
83 llvm::dbgs() << " " << kindValStr
84 << ": " << atomToDebugString(ref->target()) << "\n";
Rui Ueyamaa930d122013-12-09 00:37:19 +000085 }
86 atom = followOnNexts[atom];
87 } while (atom != start);
88 llvm::report_fatal_error("Cycle detected");
89}
90
91/// Exit if there's a cycle in a followon chain reachable from the
92/// given root atom. Uses the tortoise and hare algorithm to detect a
93/// cycle.
Nico Rieckb9d84f42014-02-24 21:14:37 +000094static void checkNoCycleInFollowonChain(const Registry &registry,
95 AtomToAtomT &followOnNexts,
Rui Ueyamaa930d122013-12-09 00:37:19 +000096 const DefinedAtom *root) {
97 const DefinedAtom *tortoise = root;
98 const DefinedAtom *hare = followOnNexts[root];
99 while (true) {
100 if (!tortoise || !hare)
101 return;
102 if (tortoise == hare)
Nico Rieckb9d84f42014-02-24 21:14:37 +0000103 showCycleDetectedError(registry, followOnNexts, tortoise);
Rui Ueyamaa930d122013-12-09 00:37:19 +0000104 tortoise = followOnNexts[tortoise];
105 hare = followOnNexts[followOnNexts[hare]];
106 }
107}
108
109static void checkReachabilityFromRoot(AtomToAtomT &followOnRoots,
110 const DefinedAtom *atom) {
111 if (!atom) return;
112 auto i = followOnRoots.find(atom);
113 if (i == followOnRoots.end()) {
Rui Ueyama2ea86392014-09-18 23:21:39 +0000114 llvm_unreachable(((Twine("Atom <") + atomToDebugString(atom) +
115 "> has no follow-on root!"))
116 .str()
117 .c_str());
Rui Ueyamaa930d122013-12-09 00:37:19 +0000118 }
119 const DefinedAtom *ap = i->second;
120 while (true) {
121 const DefinedAtom *next = followOnRoots[ap];
122 if (!next) {
Rui Ueyama2ea86392014-09-18 23:21:39 +0000123 llvm_unreachable((Twine("Atom <" + atomToDebugString(atom) +
124 "> is not reachable from its root!"))
125 .str()
126 .c_str());
Rui Ueyamaa930d122013-12-09 00:37:19 +0000127 }
128 if (next == ap)
129 return;
130 ap = next;
131 }
132}
133
134static void printDefinedAtoms(const MutableFile::DefinedAtomRange &atomRange) {
135 for (const DefinedAtom *atom : atomRange) {
136 llvm::dbgs() << " file=" << atom->file().path()
137 << ", name=" << atom->name()
138 << ", size=" << atom->size()
139 << ", type=" << atom->contentType()
140 << ", ordinal=" << atom->ordinal()
141 << "\n";
142 }
143}
144
145/// Verify that the followon chain is sane. Should not be called in
146/// release binary.
147void LayoutPass::checkFollowonChain(MutableFile::DefinedAtomRange &range) {
148 ScopedTask task(getDefaultDomain(), "LayoutPass::checkFollowonChain");
149
150 // Verify that there's no cycle in follow-on chain.
151 std::set<const DefinedAtom *> roots;
152 for (const auto &ai : _followOnRoots)
153 roots.insert(ai.second);
154 for (const DefinedAtom *root : roots)
Nico Rieckb9d84f42014-02-24 21:14:37 +0000155 checkNoCycleInFollowonChain(_registry, _followOnNexts, root);
Rui Ueyamaa930d122013-12-09 00:37:19 +0000156
157 // Verify that all the atoms in followOnNexts have references to
158 // their roots.
159 for (const auto &ai : _followOnNexts) {
160 checkReachabilityFromRoot(_followOnRoots, ai.first);
161 checkReachabilityFromRoot(_followOnRoots, ai.second);
162 }
163}
Rui Ueyama2994f6f2013-12-08 03:37:58 +0000164#endif // #ifndef NDEBUG
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000165
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000166/// The function compares atoms by sorting atoms in the following order
Shankar Easwarand6d1b522013-09-12 15:59:34 +0000167/// a) Sorts atoms by Section position preference
Rui Ueyama8be4ce22014-03-27 22:08:26 +0000168/// b) Sorts atoms by their ordinal overrides (layout-after/ingroup)
Shankar Easwarand6d1b522013-09-12 15:59:34 +0000169/// c) Sorts atoms by their permissions
170/// d) Sorts atoms by their content
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000171/// e) If custom sorter provided, let it sort
172/// f) Sorts atoms on how they appear using File Ordinality
173/// g) Sorts atoms on how they appear within the File
Rui Ueyama5af46222013-12-08 03:24:09 +0000174static bool compareAtomsSub(const LayoutPass::SortKey &lc,
175 const LayoutPass::SortKey &rc,
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000176 LayoutPass::SortOverride customSorter,
Rui Ueyama5af46222013-12-08 03:24:09 +0000177 std::string &reason) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000178 const DefinedAtom *left = lc._atom;
179 const DefinedAtom *right = rc._atom;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000180 if (left == right) {
181 reason = "same";
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000182 return false;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000183 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000184
Shankar Easwarand8da9892013-05-22 17:41:04 +0000185 // Sort by section position preference.
186 DefinedAtom::SectionPosition leftPos = left->sectionPosition();
187 DefinedAtom::SectionPosition rightPos = right->sectionPosition();
188
Shankar Easwarand8da9892013-05-22 17:41:04 +0000189 bool leftSpecialPos = (leftPos != DefinedAtom::sectionPositionAny);
190 bool rightSpecialPos = (rightPos != DefinedAtom::sectionPositionAny);
191 if (leftSpecialPos || rightSpecialPos) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000192 if (leftPos != rightPos) {
193 DEBUG(reason = formatReason("sectionPos", (int)leftPos, (int)rightPos));
Shankar Easwarand8da9892013-05-22 17:41:04 +0000194 return leftPos < rightPos;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000195 }
Shankar Easwarand8da9892013-05-22 17:41:04 +0000196 }
197
Rui Ueyama46bf8282013-10-19 03:18:18 +0000198 // Find the root of the chain if it is a part of a follow-on chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000199 const DefinedAtom *leftRoot = lc._root;
200 const DefinedAtom *rightRoot = rc._root;
Shankar Easwaranf1b341c2013-09-12 15:43:09 +0000201
202 // Sort atoms by their ordinal overrides only if they fall in the same
203 // chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000204 if (leftRoot == rightRoot) {
205 DEBUG(reason = formatReason("override", lc._override, rc._override));
206 return lc._override < rc._override;
Shankar Easwaran3c5d2c82013-05-10 16:44:02 +0000207 }
208
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000209 // Sort same permissions together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000210 DefinedAtom::ContentPermissions leftPerms = leftRoot->permissions();
211 DefinedAtom::ContentPermissions rightPerms = rightRoot->permissions();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000212
Rui Ueyama6a607b62013-10-18 02:56:31 +0000213 if (leftPerms != rightPerms) {
214 DEBUG(reason =
215 formatReason("contentPerms", (int)leftPerms, (int)rightPerms));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000216 return leftPerms < rightPerms;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000217 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000218
219 // Sort same content types together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000220 DefinedAtom::ContentType leftType = leftRoot->contentType();
221 DefinedAtom::ContentType rightType = rightRoot->contentType();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000222
Rui Ueyama6a607b62013-10-18 02:56:31 +0000223 if (leftType != rightType) {
224 DEBUG(reason = formatReason("contentType", (int)leftType, (int)rightType));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000225 return leftType < rightType;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000226 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000227
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000228 // Use custom sorter if supplied.
229 if (customSorter) {
230 bool leftBeforeRight;
231 if (customSorter(leftRoot, rightRoot, leftBeforeRight))
232 return leftBeforeRight;
233 }
234
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000235 // Sort by .o order.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000236 const File *leftFile = &leftRoot->file();
237 const File *rightFile = &rightRoot->file();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000238
Rui Ueyama6a607b62013-10-18 02:56:31 +0000239 if (leftFile != rightFile) {
240 DEBUG(reason = formatReason(".o order", (int)leftFile->ordinal(),
241 (int)rightFile->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000242 return leftFile->ordinal() < rightFile->ordinal();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000243 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000244
245 // Sort by atom order with .o file.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000246 uint64_t leftOrdinal = leftRoot->ordinal();
247 uint64_t rightOrdinal = rightRoot->ordinal();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000248
Rui Ueyama6a607b62013-10-18 02:56:31 +0000249 if (leftOrdinal != rightOrdinal) {
Rui Ueyama46bf8282013-10-19 03:18:18 +0000250 DEBUG(reason = formatReason("ordinal", (int)leftRoot->ordinal(),
251 (int)rightRoot->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000252 return leftOrdinal < rightOrdinal;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000253 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000254
Rui Ueyamacd480752013-11-27 01:33:42 +0000255 llvm::errs() << "Unordered: <" << left->name() << "> <"
256 << right->name() << ">\n";
Shankar Easwaranbcf36562013-10-11 01:50:04 +0000257 llvm_unreachable("Atoms with Same Ordinal!");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000258}
259
Rui Ueyama5af46222013-12-08 03:24:09 +0000260static bool compareAtoms(const LayoutPass::SortKey &lc,
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000261 const LayoutPass::SortKey &rc,
262 LayoutPass::SortOverride customSorter) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000263 std::string reason;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000264 bool result = compareAtomsSub(lc, rc, customSorter, reason);
Rui Ueyama6a607b62013-10-18 02:56:31 +0000265 DEBUG({
Rui Ueyama4050b202013-10-18 03:18:52 +0000266 StringRef comp = result ? "<" : ">=";
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000267 llvm::dbgs() << "Layout: '" << lc._atom->name() << "' " << comp << " '"
268 << rc._atom->name() << "' (" << reason << ")\n";
Rui Ueyama6a607b62013-10-18 02:56:31 +0000269 });
270 return result;
271}
272
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000273LayoutPass::LayoutPass(const Registry &registry, SortOverride sorter)
274 : _registry(registry), _customSorter(sorter) {}
Nico Rieckb9d84f42014-02-24 21:14:37 +0000275
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000276// Returns the atom immediately followed by the given atom in the followon
277// chain.
278const DefinedAtom *LayoutPass::findAtomFollowedBy(
279 const DefinedAtom *targetAtom) {
280 // Start from the beginning of the chain and follow the chain until
281 // we find the targetChain.
282 const DefinedAtom *atom = _followOnRoots[targetAtom];
283 while (true) {
284 const DefinedAtom *prevAtom = atom;
285 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
286 // The target atom must be in the chain of its root.
287 assert(targetFollowOnAtomsIter != _followOnNexts.end());
288 atom = targetFollowOnAtomsIter->second;
289 if (atom == targetAtom)
290 return prevAtom;
291 }
292}
293
294// Check if all the atoms followed by the given target atom are of size zero.
295// When this method is called, an atom being added is not of size zero and
296// will be added to the head of the followon chain. All the atoms between the
297// atom and the targetAtom (specified by layout-after) need to be of size zero
298// in this case. Otherwise the desired layout is impossible.
299bool LayoutPass::checkAllPrevAtomsZeroSize(const DefinedAtom *targetAtom) {
300 const DefinedAtom *atom = _followOnRoots[targetAtom];
301 while (true) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000302 if (atom == targetAtom)
303 return true;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000304 if (atom->size() != 0)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000305 // TODO: print warning that an impossible layout is being desired by the
306 // user.
307 return false;
Rui Ueyama5ec6d1a2013-05-14 01:51:56 +0000308 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
309 // The target atom must be in the chain of its root.
310 assert(targetFollowOnAtomsIter != _followOnNexts.end());
311 atom = targetFollowOnAtomsIter->second;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000312 }
313}
314
315// Set the root of all atoms in targetAtom's chain to the given root.
316void LayoutPass::setChainRoot(const DefinedAtom *targetAtom,
317 const DefinedAtom *root) {
318 // Walk through the followon chain and override each node's root.
319 while (true) {
320 _followOnRoots[targetAtom] = root;
321 AtomToAtomT::iterator targetFollowOnAtomsIter =
322 _followOnNexts.find(targetAtom);
323 if (targetFollowOnAtomsIter == _followOnNexts.end())
324 return;
325 targetAtom = targetFollowOnAtomsIter->second;
326 }
327}
328
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000329/// This pass builds the followon tables described by two DenseMaps
330/// followOnRoots and followonNexts.
331/// The followOnRoots map contains a mapping of a DefinedAtom to its root
332/// The followOnNexts map contains a mapping of what DefinedAtom follows the
333/// current Atom
334/// The algorithm follows a very simple approach
335/// a) If the atom is first seen, then make that as the root atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000336/// b) The targetAtom which this Atom contains, has the root thats set to the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000337/// root of the current atom
338/// c) If the targetAtom is part of a different tree and the root of the
339/// targetAtom is itself, Chain all the atoms that are contained in the tree
340/// to the current Tree
341/// d) If the targetAtom is part of a different chain and the root of the
342/// targetAtom until the targetAtom has all atoms of size 0, then chain the
343/// targetAtoms and its tree to the current chain
344void LayoutPass::buildFollowOnTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000345 ScopedTask task(getDefaultDomain(), "LayoutPass::buildFollowOnTable");
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000346 // Set the initial size of the followon and the followonNext hash to the
347 // number of atoms that we have.
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000348 _followOnRoots.resize(range.size());
349 _followOnNexts.resize(range.size());
Rui Ueyama0196d1062013-05-14 16:53:59 +0000350 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000351 for (const Reference *r : *ai) {
Rui Ueyamac9411c32014-03-21 21:46:49 +0000352 if (r->kindNamespace() != lld::Reference::KindNamespace::all ||
353 r->kindValue() != lld::Reference::kindLayoutAfter)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000354 continue;
Rui Ueyamac1800be2013-11-05 01:37:40 +0000355 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000356 _followOnNexts[ai] = targetAtom;
357
Alp Toker22593762013-12-02 01:28:14 +0000358 // If we find a followon for the first time, let's make that atom as the
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000359 // root atom.
360 if (_followOnRoots.count(ai) == 0)
361 _followOnRoots[ai] = ai;
362
363 auto iter = _followOnRoots.find(targetAtom);
364 if (iter == _followOnRoots.end()) {
Alp Toker22593762013-12-02 01:28:14 +0000365 // If the targetAtom is not a root of any chain, let's make the root of
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000366 // the targetAtom to the root of the current chain.
Rui Ueyamaa821d322014-07-25 19:46:31 +0000367
368 // The expression m[i] = m[j] where m is a DenseMap and i != j is not
369 // safe. m[j] returns a reference, which would be invalidated when a
370 // rehashing occurs. If rehashing occurs to make room for m[i], m[j]
371 // becomes invalid, and that invalid reference would be used as the RHS
372 // value of the expression.
373 // Copy the value to workaround.
374 const DefinedAtom *tmp = _followOnRoots[ai];
375 _followOnRoots[targetAtom] = tmp;
Rui Ueyamac9411c32014-03-21 21:46:49 +0000376 continue;
377 }
378 if (iter->second == targetAtom) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000379 // If the targetAtom is the root of a chain, the chain becomes part of
380 // the current chain. Rewrite the subchain's root to the current
381 // chain's root.
382 setChainRoot(targetAtom, _followOnRoots[ai]);
Rui Ueyamac9411c32014-03-21 21:46:49 +0000383 continue;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000384 }
Rui Ueyamac9411c32014-03-21 21:46:49 +0000385 // The targetAtom is already a part of a chain. If the current atom is
386 // of size zero, we can insert it in the middle of the chain just
387 // before the target atom, while not breaking other atom's followon
388 // relationships. If it's not, we can only insert the current atom at
389 // the beginning of the chain. All the atoms followed by the target
390 // atom must be of size zero in that case to satisfy the followon
391 // relationships.
392 size_t currentAtomSize = ai->size();
393 if (currentAtomSize == 0) {
394 const DefinedAtom *targetPrevAtom = findAtomFollowedBy(targetAtom);
395 _followOnNexts[targetPrevAtom] = ai;
Rui Ueyamaa821d322014-07-25 19:46:31 +0000396 const DefinedAtom *tmp = _followOnRoots[targetPrevAtom];
397 _followOnRoots[ai] = tmp;
Rui Ueyamac9411c32014-03-21 21:46:49 +0000398 continue;
399 }
400 if (!checkAllPrevAtomsZeroSize(targetAtom))
401 break;
402 _followOnNexts[ai] = _followOnRoots[targetAtom];
403 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000404 }
405 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000406}
407
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000408/// Build an ordinal override map by traversing the followon chain, and
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000409/// assigning ordinals to each atom, if the atoms have their ordinals
410/// already assigned skip the atom and move to the next. This is the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000411/// main map thats used to sort the atoms while comparing two atoms together
412void LayoutPass::buildOrdinalOverrideMap(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000413 ScopedTask task(getDefaultDomain(), "LayoutPass::buildOrdinalOverrideMap");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000414 uint64_t index = 0;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000415 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000416 const DefinedAtom *atom = ai;
Michael J. Spencer1ecf8902013-03-12 00:10:00 +0000417 if (_ordinalOverrideMap.find(atom) != _ordinalOverrideMap.end())
418 continue;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000419 AtomToAtomT::iterator start = _followOnRoots.find(atom);
Rui Ueyamac9411c32014-03-21 21:46:49 +0000420 if (start == _followOnRoots.end())
421 continue;
422 for (const DefinedAtom *nextAtom = start->second; nextAtom != NULL;
423 nextAtom = _followOnNexts[nextAtom]) {
424 AtomToOrdinalT::iterator pos = _ordinalOverrideMap.find(nextAtom);
425 if (pos == _ordinalOverrideMap.end())
426 _ordinalOverrideMap[nextAtom] = index++;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000427 }
428 }
429}
430
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000431std::vector<LayoutPass::SortKey>
432LayoutPass::decorate(MutableFile::DefinedAtomRange &atomRange) const {
433 std::vector<SortKey> ret;
434 for (const DefinedAtom *atom : atomRange) {
435 auto ri = _followOnRoots.find(atom);
436 auto oi = _ordinalOverrideMap.find(atom);
437 const DefinedAtom *root = (ri == _followOnRoots.end()) ? atom : ri->second;
438 uint64_t override = (oi == _ordinalOverrideMap.end()) ? 0 : oi->second;
439 ret.push_back(SortKey(atom, root, override));
440 }
441 return ret;
442}
443
444void LayoutPass::undecorate(MutableFile::DefinedAtomRange &atomRange,
445 std::vector<SortKey> &keys) const {
446 size_t i = 0;
447 for (SortKey &k : keys)
448 atomRange[i++] = k._atom;
449}
450
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000451/// Perform the actual pass
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000452void LayoutPass::perform(std::unique_ptr<MutableFile> &mergedFile) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000453 // sort the atoms
Michael J. Spencerbd66d042013-05-28 18:55:39 +0000454 ScopedTask task(getDefaultDomain(), "LayoutPass");
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000455 MutableFile::DefinedAtomRange atomRange = mergedFile->definedAtoms();
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000456
457 // Build follow on tables
458 buildFollowOnTable(atomRange);
459
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000460 // Check the structure of followon graph if running in debug mode.
461 DEBUG(checkFollowonChain(atomRange));
462
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000463 // Build override maps
464 buildOrdinalOverrideMap(atomRange);
465
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000466 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000467 llvm::dbgs() << "unsorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000468 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000469 });
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000470
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000471 std::vector<LayoutPass::SortKey> vec = decorate(atomRange);
Rui Ueyama87d10ef2015-01-26 20:18:37 +0000472 parallel_sort(vec.begin(), vec.end(),
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000473 [&](const LayoutPass::SortKey &l, const LayoutPass::SortKey &r) -> bool {
474 return compareAtoms(l, r, _customSorter);
475 });
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000476 DEBUG(checkTransitivity(vec));
477 undecorate(atomRange, vec);
Rui Ueyama46bf8282013-10-19 03:18:18 +0000478
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000479 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000480 llvm::dbgs() << "sorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000481 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000482 });
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000483}
Rui Ueyama00762152015-02-05 20:05:33 +0000484
485void addLayoutPass(PassManager &pm, const MachOLinkingContext &ctx) {
486 pm.add(std::unique_ptr<Pass>(new LayoutPass(
487 ctx.registry(), [&](const DefinedAtom * left, const DefinedAtom * right,
488 bool & leftBeforeRight)
489 ->bool {
490 return ctx.customAtomOrderer(left, right, leftBeforeRight);
491 })));
492}
493
494} // namespace mach_o
495} // namespace lld