blob: 61b53932ad8ece70ac09581dd25c3e1e6238dbb5 [file] [log] [blame]
Shankar Easwaran2bc24922013-10-29 05:12:14 +00001//===--Passes/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
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000010#define DEBUG_TYPE "LayoutPass"
11
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000012#include <algorithm>
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +000013#include <set>
14
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000015#include "lld/Passes/LayoutPass.h"
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +000016#include "lld/Core/Instrumentation.h"
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +000017
18#include "llvm/ADT/Twine.h"
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000019#include "llvm/Support/Debug.h"
20
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000021using namespace lld;
22
Rui Ueyama5af46222013-12-08 03:24:09 +000023static bool compareAtoms(const LayoutPass::SortKey &,
24 const LayoutPass::SortKey &);
25
Rui Ueyama2994f6f2013-12-08 03:37:58 +000026#ifndef NDEBUG
Rui Ueyama6a607b62013-10-18 02:56:31 +000027// Return "reason (leftval, rightval)"
Rui Ueyama5af46222013-12-08 03:24:09 +000028static std::string formatReason(StringRef reason, int leftVal, int rightVal) {
Rui Ueyama6a607b62013-10-18 02:56:31 +000029 Twine msg =
30 Twine(reason) + " (" + Twine(leftVal) + ", " + Twine(rightVal) + ")";
Rui Ueyamac74157c2013-11-01 20:40:33 +000031 return msg.str();
Rui Ueyama6a607b62013-10-18 02:56:31 +000032}
Rui Ueyama46bf8282013-10-19 03:18:18 +000033
34// Less-than relationship of two atoms must be transitive, which is, if a < b
35// and b < c, a < c must be true. This function checks the transitivity by
36// checking the sort results.
Rui Ueyama5af46222013-12-08 03:24:09 +000037static void checkTransitivity(std::vector<LayoutPass::SortKey> &vec) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000038 for (auto i = vec.begin(), e = vec.end(); (i + 1) != e; ++i) {
39 for (auto j = i + 1; j != e; ++j) {
40 assert(compareAtoms(*i, *j));
41 assert(!compareAtoms(*j, *i));
Rui Ueyama46bf8282013-10-19 03:18:18 +000042 }
43 }
Rui Ueyama6a607b62013-10-18 02:56:31 +000044}
Rui Ueyamaa930d122013-12-09 00:37:19 +000045
46// Helper functions to check follow-on graph.
47typedef llvm::DenseMap<const DefinedAtom *, const DefinedAtom *> AtomToAtomT;
48
49static std::string atomToDebugString(const Atom *atom) {
50 const DefinedAtom *definedAtom = dyn_cast<DefinedAtom>(atom);
51 std::string str;
52 llvm::raw_string_ostream s(str);
53 if (definedAtom->name().empty())
54 s << "<anonymous " << definedAtom << ">";
55 else
56 s << definedAtom->name();
57 s << " in ";
58 if (definedAtom->customSectionName().empty())
59 s << "<anonymous>";
60 else
61 s << definedAtom->customSectionName();
62 s.flush();
63 return str;
64}
65
66static void showCycleDetectedError(AtomToAtomT &followOnNexts,
67 const DefinedAtom *atom) {
68 const DefinedAtom *start = atom;
69 llvm::dbgs() << "There's a cycle in a follow-on chain!\n";
70 do {
71 llvm::dbgs() << " " << atomToDebugString(atom) << "\n";
72 for (const Reference *ref : *atom) {
73 llvm::dbgs() << " " << ref->kindToString()
74 << ": " << atomToDebugString(ref->target()) << "\n";
75 }
76 atom = followOnNexts[atom];
77 } while (atom != start);
78 llvm::report_fatal_error("Cycle detected");
79}
80
81/// Exit if there's a cycle in a followon chain reachable from the
82/// given root atom. Uses the tortoise and hare algorithm to detect a
83/// cycle.
84static void checkNoCycleInFollowonChain(AtomToAtomT &followOnNexts,
85 const DefinedAtom *root) {
86 const DefinedAtom *tortoise = root;
87 const DefinedAtom *hare = followOnNexts[root];
88 while (true) {
89 if (!tortoise || !hare)
90 return;
91 if (tortoise == hare)
92 showCycleDetectedError(followOnNexts, tortoise);
93 tortoise = followOnNexts[tortoise];
94 hare = followOnNexts[followOnNexts[hare]];
95 }
96}
97
98static void checkReachabilityFromRoot(AtomToAtomT &followOnRoots,
99 const DefinedAtom *atom) {
100 if (!atom) return;
101 auto i = followOnRoots.find(atom);
102 if (i == followOnRoots.end()) {
103 Twine msg(Twine("Atom <") + atomToDebugString(atom)
104 + "> has no follow-on root!");
105 llvm_unreachable(msg.str().c_str());
106 }
107 const DefinedAtom *ap = i->second;
108 while (true) {
109 const DefinedAtom *next = followOnRoots[ap];
110 if (!next) {
111 Twine msg(Twine("Atom <" + atomToDebugString(atom)
112 + "> is not reachable from its root!"));
113 llvm_unreachable(msg.str().c_str());
114 }
115 if (next == ap)
116 return;
117 ap = next;
118 }
119}
120
121static void printDefinedAtoms(const MutableFile::DefinedAtomRange &atomRange) {
122 for (const DefinedAtom *atom : atomRange) {
123 llvm::dbgs() << " file=" << atom->file().path()
124 << ", name=" << atom->name()
125 << ", size=" << atom->size()
126 << ", type=" << atom->contentType()
127 << ", ordinal=" << atom->ordinal()
128 << "\n";
129 }
130}
131
132/// Verify that the followon chain is sane. Should not be called in
133/// release binary.
134void LayoutPass::checkFollowonChain(MutableFile::DefinedAtomRange &range) {
135 ScopedTask task(getDefaultDomain(), "LayoutPass::checkFollowonChain");
136
137 // Verify that there's no cycle in follow-on chain.
138 std::set<const DefinedAtom *> roots;
139 for (const auto &ai : _followOnRoots)
140 roots.insert(ai.second);
141 for (const DefinedAtom *root : roots)
142 checkNoCycleInFollowonChain(_followOnNexts, root);
143
144 // Verify that all the atoms in followOnNexts have references to
145 // their roots.
146 for (const auto &ai : _followOnNexts) {
147 checkReachabilityFromRoot(_followOnRoots, ai.first);
148 checkReachabilityFromRoot(_followOnRoots, ai.second);
149 }
150}
Rui Ueyama2994f6f2013-12-08 03:37:58 +0000151#endif // #ifndef NDEBUG
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000152
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000153/// The function compares atoms by sorting atoms in the following order
Shankar Easwarand6d1b522013-09-12 15:59:34 +0000154/// a) Sorts atoms by Section position preference
155/// b) Sorts atoms by their ordinal overrides
156/// (layout-after/layout-before/ingroup)
157/// c) Sorts atoms by their permissions
158/// d) Sorts atoms by their content
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000159/// e) Sorts atoms on how they appear using File Ordinality
160/// f) Sorts atoms on how they appear within the File
Rui Ueyama5af46222013-12-08 03:24:09 +0000161static bool compareAtomsSub(const LayoutPass::SortKey &lc,
162 const LayoutPass::SortKey &rc,
163 std::string &reason) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000164 const DefinedAtom *left = lc._atom;
165 const DefinedAtom *right = rc._atom;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000166 if (left == right) {
167 reason = "same";
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000168 return false;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000169 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000170
Shankar Easwarand8da9892013-05-22 17:41:04 +0000171 // Sort by section position preference.
172 DefinedAtom::SectionPosition leftPos = left->sectionPosition();
173 DefinedAtom::SectionPosition rightPos = right->sectionPosition();
174
Shankar Easwarand8da9892013-05-22 17:41:04 +0000175 bool leftSpecialPos = (leftPos != DefinedAtom::sectionPositionAny);
176 bool rightSpecialPos = (rightPos != DefinedAtom::sectionPositionAny);
177 if (leftSpecialPos || rightSpecialPos) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000178 if (leftPos != rightPos) {
179 DEBUG(reason = formatReason("sectionPos", (int)leftPos, (int)rightPos));
Shankar Easwarand8da9892013-05-22 17:41:04 +0000180 return leftPos < rightPos;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000181 }
Shankar Easwarand8da9892013-05-22 17:41:04 +0000182 }
183
Rui Ueyama46bf8282013-10-19 03:18:18 +0000184 // Find the root of the chain if it is a part of a follow-on chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000185 const DefinedAtom *leftRoot = lc._root;
186 const DefinedAtom *rightRoot = rc._root;
Shankar Easwaranf1b341c2013-09-12 15:43:09 +0000187
188 // Sort atoms by their ordinal overrides only if they fall in the same
189 // chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000190 if (leftRoot == rightRoot) {
191 DEBUG(reason = formatReason("override", lc._override, rc._override));
192 return lc._override < rc._override;
Shankar Easwaran3c5d2c82013-05-10 16:44:02 +0000193 }
194
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000195 // Sort same permissions together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000196 DefinedAtom::ContentPermissions leftPerms = leftRoot->permissions();
197 DefinedAtom::ContentPermissions rightPerms = rightRoot->permissions();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000198
Rui Ueyama6a607b62013-10-18 02:56:31 +0000199 if (leftPerms != rightPerms) {
200 DEBUG(reason =
201 formatReason("contentPerms", (int)leftPerms, (int)rightPerms));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000202 return leftPerms < rightPerms;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000203 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000204
205 // Sort same content types together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000206 DefinedAtom::ContentType leftType = leftRoot->contentType();
207 DefinedAtom::ContentType rightType = rightRoot->contentType();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000208
Rui Ueyama6a607b62013-10-18 02:56:31 +0000209 if (leftType != rightType) {
210 DEBUG(reason = formatReason("contentType", (int)leftType, (int)rightType));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000211 return leftType < rightType;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000212 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000213
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000214 // Sort by .o order.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000215 const File *leftFile = &leftRoot->file();
216 const File *rightFile = &rightRoot->file();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000217
Rui Ueyama6a607b62013-10-18 02:56:31 +0000218 if (leftFile != rightFile) {
219 DEBUG(reason = formatReason(".o order", (int)leftFile->ordinal(),
220 (int)rightFile->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000221 return leftFile->ordinal() < rightFile->ordinal();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000222 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000223
224 // Sort by atom order with .o file.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000225 uint64_t leftOrdinal = leftRoot->ordinal();
226 uint64_t rightOrdinal = rightRoot->ordinal();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000227
Rui Ueyama6a607b62013-10-18 02:56:31 +0000228 if (leftOrdinal != rightOrdinal) {
Rui Ueyama46bf8282013-10-19 03:18:18 +0000229 DEBUG(reason = formatReason("ordinal", (int)leftRoot->ordinal(),
230 (int)rightRoot->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000231 return leftOrdinal < rightOrdinal;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000232 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000233
Rui Ueyamacd480752013-11-27 01:33:42 +0000234 llvm::errs() << "Unordered: <" << left->name() << "> <"
235 << right->name() << ">\n";
Shankar Easwaranbcf36562013-10-11 01:50:04 +0000236 llvm_unreachable("Atoms with Same Ordinal!");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000237}
238
Rui Ueyama5af46222013-12-08 03:24:09 +0000239static bool compareAtoms(const LayoutPass::SortKey &lc,
240 const LayoutPass::SortKey &rc) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000241 std::string reason;
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000242 bool result = compareAtomsSub(lc, rc, reason);
Rui Ueyama6a607b62013-10-18 02:56:31 +0000243 DEBUG({
Rui Ueyama4050b202013-10-18 03:18:52 +0000244 StringRef comp = result ? "<" : ">=";
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000245 llvm::dbgs() << "Layout: '" << lc._atom->name() << "' " << comp << " '"
246 << rc._atom->name() << "' (" << reason << ")\n";
Rui Ueyama6a607b62013-10-18 02:56:31 +0000247 });
248 return result;
249}
250
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000251// Returns the atom immediately followed by the given atom in the followon
252// chain.
253const DefinedAtom *LayoutPass::findAtomFollowedBy(
254 const DefinedAtom *targetAtom) {
255 // Start from the beginning of the chain and follow the chain until
256 // we find the targetChain.
257 const DefinedAtom *atom = _followOnRoots[targetAtom];
258 while (true) {
259 const DefinedAtom *prevAtom = atom;
260 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
261 // The target atom must be in the chain of its root.
262 assert(targetFollowOnAtomsIter != _followOnNexts.end());
263 atom = targetFollowOnAtomsIter->second;
264 if (atom == targetAtom)
265 return prevAtom;
266 }
267}
268
269// Check if all the atoms followed by the given target atom are of size zero.
270// When this method is called, an atom being added is not of size zero and
271// will be added to the head of the followon chain. All the atoms between the
272// atom and the targetAtom (specified by layout-after) need to be of size zero
273// in this case. Otherwise the desired layout is impossible.
274bool LayoutPass::checkAllPrevAtomsZeroSize(const DefinedAtom *targetAtom) {
275 const DefinedAtom *atom = _followOnRoots[targetAtom];
276 while (true) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000277 if (atom == targetAtom)
278 return true;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000279 if (atom->size() != 0)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000280 // TODO: print warning that an impossible layout is being desired by the
281 // user.
282 return false;
Rui Ueyama5ec6d1a2013-05-14 01:51:56 +0000283 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
284 // The target atom must be in the chain of its root.
285 assert(targetFollowOnAtomsIter != _followOnNexts.end());
286 atom = targetFollowOnAtomsIter->second;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000287 }
288}
289
290// Set the root of all atoms in targetAtom's chain to the given root.
291void LayoutPass::setChainRoot(const DefinedAtom *targetAtom,
292 const DefinedAtom *root) {
293 // Walk through the followon chain and override each node's root.
294 while (true) {
295 _followOnRoots[targetAtom] = root;
296 AtomToAtomT::iterator targetFollowOnAtomsIter =
297 _followOnNexts.find(targetAtom);
298 if (targetFollowOnAtomsIter == _followOnNexts.end())
299 return;
300 targetAtom = targetFollowOnAtomsIter->second;
301 }
302}
303
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000304/// This pass builds the followon tables described by two DenseMaps
305/// followOnRoots and followonNexts.
306/// The followOnRoots map contains a mapping of a DefinedAtom to its root
307/// The followOnNexts map contains a mapping of what DefinedAtom follows the
308/// current Atom
309/// The algorithm follows a very simple approach
310/// a) If the atom is first seen, then make that as the root atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000311/// b) The targetAtom which this Atom contains, has the root thats set to the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000312/// root of the current atom
313/// c) If the targetAtom is part of a different tree and the root of the
314/// targetAtom is itself, Chain all the atoms that are contained in the tree
315/// to the current Tree
316/// d) If the targetAtom is part of a different chain and the root of the
317/// targetAtom until the targetAtom has all atoms of size 0, then chain the
318/// targetAtoms and its tree to the current chain
319void LayoutPass::buildFollowOnTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000320 ScopedTask task(getDefaultDomain(), "LayoutPass::buildFollowOnTable");
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000321 // Set the initial size of the followon and the followonNext hash to the
322 // number of atoms that we have.
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000323 _followOnRoots.resize(range.size());
324 _followOnNexts.resize(range.size());
Rui Ueyama0196d1062013-05-14 16:53:59 +0000325 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000326 for (const Reference *r : *ai) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000327 if (r->kind() != lld::Reference::kindLayoutAfter)
328 continue;
Rui Ueyamac1800be2013-11-05 01:37:40 +0000329 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000330 _followOnNexts[ai] = targetAtom;
331
Alp Toker22593762013-12-02 01:28:14 +0000332 // If we find a followon for the first time, let's make that atom as the
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000333 // root atom.
334 if (_followOnRoots.count(ai) == 0)
335 _followOnRoots[ai] = ai;
336
337 auto iter = _followOnRoots.find(targetAtom);
338 if (iter == _followOnRoots.end()) {
Alp Toker22593762013-12-02 01:28:14 +0000339 // If the targetAtom is not a root of any chain, let's make the root of
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000340 // the targetAtom to the root of the current chain.
341 _followOnRoots[targetAtom] = _followOnRoots[ai];
342 } else if (iter->second == targetAtom) {
343 // If the targetAtom is the root of a chain, the chain becomes part of
344 // the current chain. Rewrite the subchain's root to the current
345 // chain's root.
346 setChainRoot(targetAtom, _followOnRoots[ai]);
347 } else {
348 // The targetAtom is already a part of a chain. If the current atom is
349 // of size zero, we can insert it in the middle of the chain just
350 // before the target atom, while not breaking other atom's followon
351 // relationships. If it's not, we can only insert the current atom at
352 // the beginning of the chain. All the atoms followed by the target
353 // atom must be of size zero in that case to satisfy the followon
354 // relationships.
Rui Ueyama0196d1062013-05-14 16:53:59 +0000355 size_t currentAtomSize = ai->size();
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000356 if (currentAtomSize == 0) {
357 const DefinedAtom *targetPrevAtom = findAtomFollowedBy(targetAtom);
358 _followOnNexts[targetPrevAtom] = ai;
359 _followOnRoots[ai] = _followOnRoots[targetPrevAtom];
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000360 } else {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000361 if (!checkAllPrevAtomsZeroSize(targetAtom))
362 break;
363 _followOnNexts[ai] = _followOnRoots[targetAtom];
364 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
365 }
366 }
367 }
368 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000369}
370
371/// This pass builds the followon tables using InGroup relationships
372/// The algorithm follows a very simple approach
373/// a) If the rootAtom is not part of any root, create a new root with the
374/// as the head
375/// b) If the current Atom root is not found, then make the current atoms root
376/// point to the rootAtom
377/// c) If the root of the current Atom is itself a root of some other tree
378/// make all the atoms in the chain point to the ingroup reference
379/// d) Check to see if the current atom is part of the chain from the rootAtom
380/// if not add the atom to the chain, so that the current atom is part of the
381/// the chain where the rootAtom is in
382void LayoutPass::buildInGroupTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000383 ScopedTask task(getDefaultDomain(), "LayoutPass::buildInGroupTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000384 // This table would convert precededby references to follow on
385 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000386 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000387 for (const Reference *r : *ai) {
388 if (r->kind() == lld::Reference::kindInGroup) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000389 const DefinedAtom *rootAtom = dyn_cast<DefinedAtom>(r->target());
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000390 // If the root atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000391 // create a new root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000392 if (_followOnRoots.count(rootAtom) == 0) {
393 _followOnRoots[rootAtom] = rootAtom;
394 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000395 // If the current Atom has not been seen yet and there is no root
396 // that has been set, set the root of the atom to the targetAtom
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000397 // as the targetAtom points to the ingroup root
398 auto iter = _followOnRoots.find(ai);
399 if (iter == _followOnRoots.end()) {
400 _followOnRoots[ai] = rootAtom;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000401 } else if (iter->second == ai) {
402 if (iter->second != rootAtom)
403 setChainRoot(iter->second, rootAtom);
404 } else {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000405 // TODO : Flag an error that the root of the tree
406 // is different, Here is an example
407 // Say there are atoms
408 // chain 1 : a->b->c
409 // chain 2 : d->e->f
410 // and e,f have their ingroup reference as a
411 // this could happen only if the root of e,f that is d
412 // has root as 'a'
413 continue;
414 }
415
416 // Check if the current atom is part of the chain
417 bool isAtomInChain = false;
418 const DefinedAtom *lastAtom = rootAtom;
419 while (true) {
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000420 AtomToAtomT::iterator followOnAtomsIter =
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000421 _followOnNexts.find(lastAtom);
422 if (followOnAtomsIter != _followOnNexts.end()) {
423 lastAtom = followOnAtomsIter->second;
424 if (lastAtom == ai) {
425 isAtomInChain = true;
426 break;
427 }
428 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000429 else
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000430 break;
431 } // findAtomInChain
432
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000433 if (!isAtomInChain)
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000434 _followOnNexts[lastAtom] = ai;
435 }
436 }
437 }
438}
439
440/// This pass builds the followon tables using Preceded By relationships
441/// The algorithm follows a very simple approach
442/// a) If the targetAtom is not part of any root and the current atom is not
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000443/// part of any root, create a chain with the current atom as root and
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000444/// the targetAtom as following the current atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000445/// b) Chain the targetAtom to the current Atom if the targetAtom is not part
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000446/// of any chain and the currentAtom has no followOn's
447/// c) If the targetAtom is part of a different tree and the root of the
448/// targetAtom is itself, and if the current atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000449/// chain all the atoms together
450/// d) If the current atom has no followon and the root of the targetAtom is
451/// not equal to the root of the current atom(the targetAtom is not in the
452/// same chain), chain all the atoms that are lead by the targetAtom into
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000453/// the current chain
454void LayoutPass::buildPrecededByTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000455 ScopedTask task(getDefaultDomain(), "LayoutPass::buildPrecededByTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000456 // This table would convert precededby references to follow on
457 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000458 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000459 for (const Reference *r : *ai) {
460 if (r->kind() == lld::Reference::kindLayoutBefore) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000461 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000462 // Is the targetAtom not chained
463 if (_followOnRoots.count(targetAtom) == 0) {
464 // Is the current atom not part of any root ?
465 if (_followOnRoots.count(ai) == 0) {
466 _followOnRoots[ai] = ai;
467 _followOnNexts[ai] = targetAtom;
468 _followOnRoots[targetAtom] = _followOnRoots[ai];
469 } else if (_followOnNexts.count(ai) == 0) {
470 // Chain the targetAtom to the current Atom
471 // if the currentAtom has no followon references
472 _followOnNexts[ai] = targetAtom;
473 _followOnRoots[targetAtom] = _followOnRoots[ai];
474 }
475 } else if (_followOnRoots.find(targetAtom)->second == targetAtom) {
476 // Is the targetAtom in chain with the targetAtom as the root ?
477 bool changeRoots = false;
478 if (_followOnRoots.count(ai) == 0) {
479 _followOnRoots[ai] = ai;
480 _followOnNexts[ai] = targetAtom;
481 _followOnRoots[targetAtom] = _followOnRoots[ai];
482 changeRoots = true;
483 } else if (_followOnNexts.count(ai) == 0) {
484 // Chain the targetAtom to the current Atom
485 // if the currentAtom has no followon references
486 if (_followOnRoots[ai] != _followOnRoots[targetAtom]) {
487 _followOnNexts[ai] = targetAtom;
488 _followOnRoots[targetAtom] = _followOnRoots[ai];
489 changeRoots = true;
490 }
491 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000492 // Change the roots of the targetAtom and its chain to
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000493 // the current atoms root
494 if (changeRoots) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000495 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
496 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000497 } // Is targetAtom root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000498 } // kindLayoutBefore
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000499 } // Reference
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000500 } // atom iteration
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000501} // end function
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000502
503
504/// Build an ordinal override map by traversing the followon chain, and
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000505/// assigning ordinals to each atom, if the atoms have their ordinals
506/// already assigned skip the atom and move to the next. This is the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000507/// main map thats used to sort the atoms while comparing two atoms together
508void LayoutPass::buildOrdinalOverrideMap(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000509 ScopedTask task(getDefaultDomain(), "LayoutPass::buildOrdinalOverrideMap");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000510 uint64_t index = 0;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000511 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000512 const DefinedAtom *atom = ai;
Michael J. Spencer1ecf8902013-03-12 00:10:00 +0000513 if (_ordinalOverrideMap.find(atom) != _ordinalOverrideMap.end())
514 continue;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000515 AtomToAtomT::iterator start = _followOnRoots.find(atom);
516 if (start != _followOnRoots.end()) {
517 for (const DefinedAtom *nextAtom = start->second; nextAtom != NULL;
518 nextAtom = _followOnNexts[nextAtom]) {
519 AtomToOrdinalT::iterator pos = _ordinalOverrideMap.find(nextAtom);
520 if (pos == _ordinalOverrideMap.end()) {
521 _ordinalOverrideMap[nextAtom] = index++;
522 }
523 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000524 }
525 }
526}
527
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000528std::vector<LayoutPass::SortKey>
529LayoutPass::decorate(MutableFile::DefinedAtomRange &atomRange) const {
530 std::vector<SortKey> ret;
531 for (const DefinedAtom *atom : atomRange) {
532 auto ri = _followOnRoots.find(atom);
533 auto oi = _ordinalOverrideMap.find(atom);
534 const DefinedAtom *root = (ri == _followOnRoots.end()) ? atom : ri->second;
535 uint64_t override = (oi == _ordinalOverrideMap.end()) ? 0 : oi->second;
536 ret.push_back(SortKey(atom, root, override));
537 }
538 return ret;
539}
540
541void LayoutPass::undecorate(MutableFile::DefinedAtomRange &atomRange,
542 std::vector<SortKey> &keys) const {
543 size_t i = 0;
544 for (SortKey &k : keys)
545 atomRange[i++] = k._atom;
546}
547
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000548/// Perform the actual pass
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000549void LayoutPass::perform(std::unique_ptr<MutableFile> &mergedFile) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000550 // sort the atoms
Michael J. Spencerbd66d042013-05-28 18:55:39 +0000551 ScopedTask task(getDefaultDomain(), "LayoutPass");
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000552 MutableFile::DefinedAtomRange atomRange = mergedFile->definedAtoms();
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000553
554 // Build follow on tables
555 buildFollowOnTable(atomRange);
556
557 // Build Ingroup reference table
558 buildInGroupTable(atomRange);
559
560 // Build preceded by tables
561 buildPrecededByTable(atomRange);
562
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000563 // Check the structure of followon graph if running in debug mode.
564 DEBUG(checkFollowonChain(atomRange));
565
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000566 // Build override maps
567 buildOrdinalOverrideMap(atomRange);
568
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000569 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000570 llvm::dbgs() << "unsorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000571 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000572 });
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000573
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000574 std::vector<LayoutPass::SortKey> vec = decorate(atomRange);
575 std::sort(vec.begin(), vec.end(), compareAtoms);
576 DEBUG(checkTransitivity(vec));
577 undecorate(atomRange, vec);
Rui Ueyama46bf8282013-10-19 03:18:18 +0000578
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000579 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000580 llvm::dbgs() << "sorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000581 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000582 });
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000583}