blob: 7bca07eb16d629d1473ba5697f753107d4566b54 [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 Ueyama00762152015-02-05 20:05:33 +000012#include "lld/Core/PassManager.h"
13#include "lld/ReaderWriter/MachOLinkingContext.h"
Benjamin Kramer06a42af2015-03-02 00:48:06 +000014#include "llvm/ADT/STLExtras.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"
Zachary Turner3a57fbd2017-05-11 00:03:52 +000017#include "llvm/Support/Parallel.h"
Shankar Easwaran2b67fca2014-10-18 05:33:55 +000018#include <algorithm>
19#include <set>
Benjamin Kramerbd521202016-06-03 16:57:13 +000020#include <utility>
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000021
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000022using namespace lld;
23
Chandler Carruth9afe32d2014-04-22 03:21:31 +000024#define DEBUG_TYPE "LayoutPass"
25
Rui Ueyama00762152015-02-05 20:05:33 +000026namespace lld {
27namespace mach_o {
28
Rui Ueyama5af46222013-12-08 03:24:09 +000029static bool compareAtoms(const LayoutPass::SortKey &,
Nick Kledzik82d24bc2014-11-07 21:01:21 +000030 const LayoutPass::SortKey &,
Rui Ueyama540842c2015-02-05 20:08:04 +000031 LayoutPass::SortOverride customSorter);
Rui Ueyama5af46222013-12-08 03:24:09 +000032
Rui Ueyama2994f6f2013-12-08 03:37:58 +000033#ifndef NDEBUG
Rui Ueyama6a607b62013-10-18 02:56:31 +000034// Return "reason (leftval, rightval)"
Rui Ueyama5af46222013-12-08 03:24:09 +000035static std::string formatReason(StringRef reason, int leftVal, int rightVal) {
Rui Ueyama2ea86392014-09-18 23:21:39 +000036 return (Twine(reason) + " (" + Twine(leftVal) + ", " + Twine(rightVal) + ")")
37 .str();
Rui Ueyama6a607b62013-10-18 02:56:31 +000038}
Rui Ueyama46bf8282013-10-19 03:18:18 +000039
40// Less-than relationship of two atoms must be transitive, which is, if a < b
41// and b < c, a < c must be true. This function checks the transitivity by
42// checking the sort results.
Rui Ueyama540842c2015-02-05 20:08:04 +000043static void checkTransitivity(std::vector<LayoutPass::SortKey> &vec,
44 LayoutPass::SortOverride customSorter) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000045 for (auto i = vec.begin(), e = vec.end(); (i + 1) != e; ++i) {
46 for (auto j = i + 1; j != e; ++j) {
Rui Ueyama540842c2015-02-05 20:08:04 +000047 assert(compareAtoms(*i, *j, customSorter));
48 assert(!compareAtoms(*j, *i, customSorter));
Rui Ueyama46bf8282013-10-19 03:18:18 +000049 }
50 }
Rui Ueyama6a607b62013-10-18 02:56:31 +000051}
Rui Ueyamaa930d122013-12-09 00:37:19 +000052
53// Helper functions to check follow-on graph.
54typedef llvm::DenseMap<const DefinedAtom *, const DefinedAtom *> AtomToAtomT;
55
56static std::string atomToDebugString(const Atom *atom) {
57 const DefinedAtom *definedAtom = dyn_cast<DefinedAtom>(atom);
58 std::string str;
59 llvm::raw_string_ostream s(str);
60 if (definedAtom->name().empty())
61 s << "<anonymous " << definedAtom << ">";
62 else
63 s << definedAtom->name();
64 s << " in ";
65 if (definedAtom->customSectionName().empty())
66 s << "<anonymous>";
67 else
68 s << definedAtom->customSectionName();
69 s.flush();
70 return str;
71}
72
Nico Rieckb9d84f42014-02-24 21:14:37 +000073static void showCycleDetectedError(const Registry &registry,
74 AtomToAtomT &followOnNexts,
Rui Ueyamaa930d122013-12-09 00:37:19 +000075 const DefinedAtom *atom) {
76 const DefinedAtom *start = atom;
77 llvm::dbgs() << "There's a cycle in a follow-on chain!\n";
78 do {
79 llvm::dbgs() << " " << atomToDebugString(atom) << "\n";
80 for (const Reference *ref : *atom) {
Nico Rieckb9d84f42014-02-24 21:14:37 +000081 StringRef kindValStr;
82 if (!registry.referenceKindToString(ref->kindNamespace(), ref->kindArch(),
83 ref->kindValue(), kindValStr)) {
84 kindValStr = "<unknown>";
85 }
86 llvm::dbgs() << " " << kindValStr
87 << ": " << atomToDebugString(ref->target()) << "\n";
Rui Ueyamaa930d122013-12-09 00:37:19 +000088 }
89 atom = followOnNexts[atom];
90 } while (atom != start);
91 llvm::report_fatal_error("Cycle detected");
92}
93
94/// Exit if there's a cycle in a followon chain reachable from the
95/// given root atom. Uses the tortoise and hare algorithm to detect a
96/// cycle.
Nico Rieckb9d84f42014-02-24 21:14:37 +000097static void checkNoCycleInFollowonChain(const Registry &registry,
98 AtomToAtomT &followOnNexts,
Rui Ueyamaa930d122013-12-09 00:37:19 +000099 const DefinedAtom *root) {
100 const DefinedAtom *tortoise = root;
101 const DefinedAtom *hare = followOnNexts[root];
102 while (true) {
103 if (!tortoise || !hare)
104 return;
105 if (tortoise == hare)
Nico Rieckb9d84f42014-02-24 21:14:37 +0000106 showCycleDetectedError(registry, followOnNexts, tortoise);
Rui Ueyamaa930d122013-12-09 00:37:19 +0000107 tortoise = followOnNexts[tortoise];
108 hare = followOnNexts[followOnNexts[hare]];
109 }
110}
111
112static void checkReachabilityFromRoot(AtomToAtomT &followOnRoots,
113 const DefinedAtom *atom) {
114 if (!atom) return;
115 auto i = followOnRoots.find(atom);
116 if (i == followOnRoots.end()) {
Rui Ueyama2ea86392014-09-18 23:21:39 +0000117 llvm_unreachable(((Twine("Atom <") + atomToDebugString(atom) +
118 "> has no follow-on root!"))
119 .str()
120 .c_str());
Rui Ueyamaa930d122013-12-09 00:37:19 +0000121 }
122 const DefinedAtom *ap = i->second;
123 while (true) {
124 const DefinedAtom *next = followOnRoots[ap];
125 if (!next) {
Rui Ueyama2ea86392014-09-18 23:21:39 +0000126 llvm_unreachable((Twine("Atom <" + atomToDebugString(atom) +
127 "> is not reachable from its root!"))
128 .str()
129 .c_str());
Rui Ueyamaa930d122013-12-09 00:37:19 +0000130 }
131 if (next == ap)
132 return;
133 ap = next;
134 }
135}
136
Lang Hamesa5c7adc2016-06-28 18:42:33 +0000137static void printDefinedAtoms(const File::AtomRange<DefinedAtom> &atomRange) {
Rui Ueyamaa930d122013-12-09 00:37:19 +0000138 for (const DefinedAtom *atom : atomRange) {
139 llvm::dbgs() << " file=" << atom->file().path()
140 << ", name=" << atom->name()
141 << ", size=" << atom->size()
142 << ", type=" << atom->contentType()
143 << ", ordinal=" << atom->ordinal()
144 << "\n";
145 }
146}
147
148/// Verify that the followon chain is sane. Should not be called in
149/// release binary.
Lang Hamesa5c7adc2016-06-28 18:42:33 +0000150void LayoutPass::checkFollowonChain(const File::AtomRange<DefinedAtom> &range) {
Rui Ueyamaa930d122013-12-09 00:37:19 +0000151 ScopedTask task(getDefaultDomain(), "LayoutPass::checkFollowonChain");
152
153 // Verify that there's no cycle in follow-on chain.
154 std::set<const DefinedAtom *> roots;
155 for (const auto &ai : _followOnRoots)
156 roots.insert(ai.second);
157 for (const DefinedAtom *root : roots)
Nico Rieckb9d84f42014-02-24 21:14:37 +0000158 checkNoCycleInFollowonChain(_registry, _followOnNexts, root);
Rui Ueyamaa930d122013-12-09 00:37:19 +0000159
160 // Verify that all the atoms in followOnNexts have references to
161 // their roots.
162 for (const auto &ai : _followOnNexts) {
163 checkReachabilityFromRoot(_followOnRoots, ai.first);
164 checkReachabilityFromRoot(_followOnRoots, ai.second);
165 }
166}
Rui Ueyama2994f6f2013-12-08 03:37:58 +0000167#endif // #ifndef NDEBUG
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000168
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000169/// The function compares atoms by sorting atoms in the following order
Rui Ueyama05366772015-03-08 01:01:40 +0000170/// a) Sorts atoms by their ordinal overrides (layout-after/ingroup)
171/// b) Sorts atoms by their permissions
172/// c) Sorts atoms by their content
173/// d) Sorts atoms by custom sorter
174/// e) Sorts atoms on how they appear using File Ordinality
175/// f) Sorts atoms on how they appear within the File
Rui Ueyama5af46222013-12-08 03:24:09 +0000176static bool compareAtomsSub(const LayoutPass::SortKey &lc,
177 const LayoutPass::SortKey &rc,
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000178 LayoutPass::SortOverride customSorter,
Rui Ueyama5af46222013-12-08 03:24:09 +0000179 std::string &reason) {
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000180 const DefinedAtom *left = lc._atom.get();
181 const DefinedAtom *right = rc._atom.get();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000182 if (left == right) {
183 reason = "same";
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000184 return false;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000185 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000186
Rui Ueyama46bf8282013-10-19 03:18:18 +0000187 // Find the root of the chain if it is a part of a follow-on chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000188 const DefinedAtom *leftRoot = lc._root;
189 const DefinedAtom *rightRoot = rc._root;
Shankar Easwaranf1b341c2013-09-12 15:43:09 +0000190
191 // Sort atoms by their ordinal overrides only if they fall in the same
192 // chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000193 if (leftRoot == rightRoot) {
194 DEBUG(reason = formatReason("override", lc._override, rc._override));
195 return lc._override < rc._override;
Shankar Easwaran3c5d2c82013-05-10 16:44:02 +0000196 }
197
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000198 // Sort same permissions together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000199 DefinedAtom::ContentPermissions leftPerms = leftRoot->permissions();
200 DefinedAtom::ContentPermissions rightPerms = rightRoot->permissions();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000201
Rui Ueyama6a607b62013-10-18 02:56:31 +0000202 if (leftPerms != rightPerms) {
203 DEBUG(reason =
204 formatReason("contentPerms", (int)leftPerms, (int)rightPerms));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000205 return leftPerms < rightPerms;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000206 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000207
208 // Sort same content types together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000209 DefinedAtom::ContentType leftType = leftRoot->contentType();
210 DefinedAtom::ContentType rightType = rightRoot->contentType();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000211
Rui Ueyama6a607b62013-10-18 02:56:31 +0000212 if (leftType != rightType) {
213 DEBUG(reason = formatReason("contentType", (int)leftType, (int)rightType));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000214 return leftType < rightType;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000215 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000216
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000217 // Use custom sorter if supplied.
218 if (customSorter) {
219 bool leftBeforeRight;
220 if (customSorter(leftRoot, rightRoot, leftBeforeRight))
221 return leftBeforeRight;
222 }
223
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000224 // Sort by .o order.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000225 const File *leftFile = &leftRoot->file();
226 const File *rightFile = &rightRoot->file();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000227
Rui Ueyama6a607b62013-10-18 02:56:31 +0000228 if (leftFile != rightFile) {
229 DEBUG(reason = formatReason(".o order", (int)leftFile->ordinal(),
230 (int)rightFile->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000231 return leftFile->ordinal() < rightFile->ordinal();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000232 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000233
234 // Sort by atom order with .o file.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000235 uint64_t leftOrdinal = leftRoot->ordinal();
236 uint64_t rightOrdinal = rightRoot->ordinal();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000237
Rui Ueyama6a607b62013-10-18 02:56:31 +0000238 if (leftOrdinal != rightOrdinal) {
Rui Ueyama46bf8282013-10-19 03:18:18 +0000239 DEBUG(reason = formatReason("ordinal", (int)leftRoot->ordinal(),
240 (int)rightRoot->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000241 return leftOrdinal < rightOrdinal;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000242 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000243
Rui Ueyamacd480752013-11-27 01:33:42 +0000244 llvm::errs() << "Unordered: <" << left->name() << "> <"
245 << right->name() << ">\n";
Shankar Easwaranbcf36562013-10-11 01:50:04 +0000246 llvm_unreachable("Atoms with Same Ordinal!");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000247}
248
Rui Ueyama5af46222013-12-08 03:24:09 +0000249static bool compareAtoms(const LayoutPass::SortKey &lc,
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000250 const LayoutPass::SortKey &rc,
251 LayoutPass::SortOverride customSorter) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000252 std::string reason;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000253 bool result = compareAtomsSub(lc, rc, customSorter, reason);
Rui Ueyama6a607b62013-10-18 02:56:31 +0000254 DEBUG({
Rui Ueyama4050b202013-10-18 03:18:52 +0000255 StringRef comp = result ? "<" : ">=";
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000256 llvm::dbgs() << "Layout: '" << lc._atom.get()->name()
257 << "' " << comp << " '"
258 << rc._atom.get()->name() << "' (" << reason << ")\n";
Rui Ueyama6a607b62013-10-18 02:56:31 +0000259 });
260 return result;
261}
262
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000263LayoutPass::LayoutPass(const Registry &registry, SortOverride sorter)
Benjamin Kramerbd521202016-06-03 16:57:13 +0000264 : _registry(registry), _customSorter(std::move(sorter)) {}
Nico Rieckb9d84f42014-02-24 21:14:37 +0000265
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000266// Returns the atom immediately followed by the given atom in the followon
267// chain.
268const DefinedAtom *LayoutPass::findAtomFollowedBy(
269 const DefinedAtom *targetAtom) {
270 // Start from the beginning of the chain and follow the chain until
271 // we find the targetChain.
272 const DefinedAtom *atom = _followOnRoots[targetAtom];
273 while (true) {
274 const DefinedAtom *prevAtom = atom;
275 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
276 // The target atom must be in the chain of its root.
277 assert(targetFollowOnAtomsIter != _followOnNexts.end());
278 atom = targetFollowOnAtomsIter->second;
279 if (atom == targetAtom)
280 return prevAtom;
281 }
282}
283
284// Check if all the atoms followed by the given target atom are of size zero.
285// When this method is called, an atom being added is not of size zero and
286// will be added to the head of the followon chain. All the atoms between the
287// atom and the targetAtom (specified by layout-after) need to be of size zero
288// in this case. Otherwise the desired layout is impossible.
289bool LayoutPass::checkAllPrevAtomsZeroSize(const DefinedAtom *targetAtom) {
290 const DefinedAtom *atom = _followOnRoots[targetAtom];
291 while (true) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000292 if (atom == targetAtom)
293 return true;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000294 if (atom->size() != 0)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000295 // TODO: print warning that an impossible layout is being desired by the
296 // user.
297 return false;
Rui Ueyama5ec6d1a2013-05-14 01:51:56 +0000298 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
299 // The target atom must be in the chain of its root.
300 assert(targetFollowOnAtomsIter != _followOnNexts.end());
301 atom = targetFollowOnAtomsIter->second;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000302 }
303}
304
305// Set the root of all atoms in targetAtom's chain to the given root.
306void LayoutPass::setChainRoot(const DefinedAtom *targetAtom,
307 const DefinedAtom *root) {
308 // Walk through the followon chain and override each node's root.
309 while (true) {
310 _followOnRoots[targetAtom] = root;
311 AtomToAtomT::iterator targetFollowOnAtomsIter =
312 _followOnNexts.find(targetAtom);
313 if (targetFollowOnAtomsIter == _followOnNexts.end())
314 return;
315 targetAtom = targetFollowOnAtomsIter->second;
316 }
317}
318
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000319/// This pass builds the followon tables described by two DenseMaps
320/// followOnRoots and followonNexts.
321/// The followOnRoots map contains a mapping of a DefinedAtom to its root
322/// The followOnNexts map contains a mapping of what DefinedAtom follows the
323/// current Atom
324/// The algorithm follows a very simple approach
325/// a) If the atom is first seen, then make that as the root atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000326/// b) The targetAtom which this Atom contains, has the root thats set to the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000327/// root of the current atom
328/// c) If the targetAtom is part of a different tree and the root of the
329/// targetAtom is itself, Chain all the atoms that are contained in the tree
330/// to the current Tree
331/// d) If the targetAtom is part of a different chain and the root of the
332/// targetAtom until the targetAtom has all atoms of size 0, then chain the
333/// targetAtoms and its tree to the current chain
Lang Hamesa5c7adc2016-06-28 18:42:33 +0000334void LayoutPass::buildFollowOnTable(const File::AtomRange<DefinedAtom> &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000335 ScopedTask task(getDefaultDomain(), "LayoutPass::buildFollowOnTable");
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000336 // Set the initial size of the followon and the followonNext hash to the
337 // number of atoms that we have.
Mehdi Aminid595b082016-03-22 07:31:35 +0000338 _followOnRoots.reserve(range.size());
339 _followOnNexts.reserve(range.size());
Rui Ueyama0196d1062013-05-14 16:53:59 +0000340 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000341 for (const Reference *r : *ai) {
Rui Ueyamac9411c32014-03-21 21:46:49 +0000342 if (r->kindNamespace() != lld::Reference::KindNamespace::all ||
343 r->kindValue() != lld::Reference::kindLayoutAfter)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000344 continue;
Rui Ueyamac1800be2013-11-05 01:37:40 +0000345 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000346 _followOnNexts[ai] = targetAtom;
347
Alp Toker22593762013-12-02 01:28:14 +0000348 // If we find a followon for the first time, let's make that atom as the
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000349 // root atom.
350 if (_followOnRoots.count(ai) == 0)
351 _followOnRoots[ai] = ai;
352
353 auto iter = _followOnRoots.find(targetAtom);
354 if (iter == _followOnRoots.end()) {
Alp Toker22593762013-12-02 01:28:14 +0000355 // If the targetAtom is not a root of any chain, let's make the root of
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000356 // the targetAtom to the root of the current chain.
Rui Ueyamaa821d322014-07-25 19:46:31 +0000357
358 // The expression m[i] = m[j] where m is a DenseMap and i != j is not
359 // safe. m[j] returns a reference, which would be invalidated when a
360 // rehashing occurs. If rehashing occurs to make room for m[i], m[j]
361 // becomes invalid, and that invalid reference would be used as the RHS
362 // value of the expression.
363 // Copy the value to workaround.
364 const DefinedAtom *tmp = _followOnRoots[ai];
365 _followOnRoots[targetAtom] = tmp;
Rui Ueyamac9411c32014-03-21 21:46:49 +0000366 continue;
367 }
368 if (iter->second == targetAtom) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000369 // If the targetAtom is the root of a chain, the chain becomes part of
370 // the current chain. Rewrite the subchain's root to the current
371 // chain's root.
372 setChainRoot(targetAtom, _followOnRoots[ai]);
Rui Ueyamac9411c32014-03-21 21:46:49 +0000373 continue;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000374 }
Rui Ueyamac9411c32014-03-21 21:46:49 +0000375 // The targetAtom is already a part of a chain. If the current atom is
376 // of size zero, we can insert it in the middle of the chain just
377 // before the target atom, while not breaking other atom's followon
378 // relationships. If it's not, we can only insert the current atom at
379 // the beginning of the chain. All the atoms followed by the target
380 // atom must be of size zero in that case to satisfy the followon
381 // relationships.
382 size_t currentAtomSize = ai->size();
383 if (currentAtomSize == 0) {
384 const DefinedAtom *targetPrevAtom = findAtomFollowedBy(targetAtom);
385 _followOnNexts[targetPrevAtom] = ai;
Rui Ueyamaa821d322014-07-25 19:46:31 +0000386 const DefinedAtom *tmp = _followOnRoots[targetPrevAtom];
387 _followOnRoots[ai] = tmp;
Rui Ueyamac9411c32014-03-21 21:46:49 +0000388 continue;
389 }
390 if (!checkAllPrevAtomsZeroSize(targetAtom))
391 break;
392 _followOnNexts[ai] = _followOnRoots[targetAtom];
393 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000394 }
395 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000396}
397
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000398/// Build an ordinal override map by traversing the followon chain, and
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000399/// assigning ordinals to each atom, if the atoms have their ordinals
400/// already assigned skip the atom and move to the next. This is the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000401/// main map thats used to sort the atoms while comparing two atoms together
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000402void
Lang Hamesa5c7adc2016-06-28 18:42:33 +0000403LayoutPass::buildOrdinalOverrideMap(const File::AtomRange<DefinedAtom> &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000404 ScopedTask task(getDefaultDomain(), "LayoutPass::buildOrdinalOverrideMap");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000405 uint64_t index = 0;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000406 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000407 const DefinedAtom *atom = ai;
Michael J. Spencer1ecf8902013-03-12 00:10:00 +0000408 if (_ordinalOverrideMap.find(atom) != _ordinalOverrideMap.end())
409 continue;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000410 AtomToAtomT::iterator start = _followOnRoots.find(atom);
Rui Ueyamac9411c32014-03-21 21:46:49 +0000411 if (start == _followOnRoots.end())
412 continue;
Rui Ueyama43155d02015-10-02 00:36:00 +0000413 for (const DefinedAtom *nextAtom = start->second; nextAtom;
Rui Ueyamac9411c32014-03-21 21:46:49 +0000414 nextAtom = _followOnNexts[nextAtom]) {
415 AtomToOrdinalT::iterator pos = _ordinalOverrideMap.find(nextAtom);
416 if (pos == _ordinalOverrideMap.end())
417 _ordinalOverrideMap[nextAtom] = index++;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000418 }
419 }
420}
421
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000422std::vector<LayoutPass::SortKey>
Lang Hamesa5c7adc2016-06-28 18:42:33 +0000423LayoutPass::decorate(File::AtomRange<DefinedAtom> &atomRange) const {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000424 std::vector<SortKey> ret;
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000425 for (OwningAtomPtr<DefinedAtom> &atom : atomRange.owning_ptrs()) {
426 auto ri = _followOnRoots.find(atom.get());
427 auto oi = _ordinalOverrideMap.find(atom.get());
428 const auto *root = (ri == _followOnRoots.end()) ? atom.get() : ri->second;
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000429 uint64_t override = (oi == _ordinalOverrideMap.end()) ? 0 : oi->second;
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000430 ret.push_back(SortKey(std::move(atom), root, override));
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000431 }
432 return ret;
433}
434
Lang Hamesa5c7adc2016-06-28 18:42:33 +0000435void LayoutPass::undecorate(File::AtomRange<DefinedAtom> &atomRange,
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000436 std::vector<SortKey> &keys) const {
437 size_t i = 0;
438 for (SortKey &k : keys)
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000439 atomRange[i++] = std::move(k._atom);
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000440}
441
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000442/// Perform the actual pass
Pete Cooperc73c9d22016-03-30 20:36:31 +0000443llvm::Error LayoutPass::perform(SimpleFile &mergedFile) {
Pete Cooper3e8f5652015-12-16 19:12:49 +0000444 DEBUG(llvm::dbgs() << "******** Laying out atoms:\n");
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000445 // sort the atoms
Michael J. Spencerbd66d042013-05-28 18:55:39 +0000446 ScopedTask task(getDefaultDomain(), "LayoutPass");
Lang Hamesa5c7adc2016-06-28 18:42:33 +0000447 File::AtomRange<DefinedAtom> atomRange = mergedFile.defined();
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000448
449 // Build follow on tables
450 buildFollowOnTable(atomRange);
451
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000452 // Check the structure of followon graph if running in debug mode.
453 DEBUG(checkFollowonChain(atomRange));
454
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000455 // Build override maps
456 buildOrdinalOverrideMap(atomRange);
457
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000458 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000459 llvm::dbgs() << "unsorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000460 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000461 });
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000462
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000463 std::vector<LayoutPass::SortKey> vec = decorate(atomRange);
Zachary Turner3a57fbd2017-05-11 00:03:52 +0000464 sort(llvm::parallel::par, vec.begin(), vec.end(),
Zachary Turner092c7672017-05-10 01:16:22 +0000465 [&](const LayoutPass::SortKey &l, const LayoutPass::SortKey &r) -> bool {
466 return compareAtoms(l, r, _customSorter);
467 });
Rui Ueyama540842c2015-02-05 20:08:04 +0000468 DEBUG(checkTransitivity(vec, _customSorter));
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000469 undecorate(atomRange, vec);
Rui Ueyama46bf8282013-10-19 03:18:18 +0000470
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000471 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000472 llvm::dbgs() << "sorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000473 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000474 });
Lang Hamesb09c2c62015-06-19 17:51:46 +0000475
Pete Cooper3e8f5652015-12-16 19:12:49 +0000476 DEBUG(llvm::dbgs() << "******** Finished laying out atoms\n");
Mehdi Aminic1edf562016-11-11 04:29:25 +0000477 return llvm::Error::success();
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000478}
Rui Ueyama00762152015-02-05 20:05:33 +0000479
480void addLayoutPass(PassManager &pm, const MachOLinkingContext &ctx) {
Rui Ueyama92634be2015-02-06 22:44:16 +0000481 pm.add(llvm::make_unique<LayoutPass>(
Rui Ueyama00762152015-02-05 20:05:33 +0000482 ctx.registry(), [&](const DefinedAtom * left, const DefinedAtom * right,
Rui Ueyama540842c2015-02-05 20:08:04 +0000483 bool & leftBeforeRight) ->bool {
Rui Ueyama00762152015-02-05 20:05:33 +0000484 return ctx.customAtomOrderer(left, right, leftBeforeRight);
Rui Ueyama92634be2015-02-06 22:44:16 +0000485 }));
Rui Ueyama00762152015-02-05 20:05:33 +0000486}
487
488} // namespace mach_o
489} // namespace lld