blob: d58fbcf3a96073c195d8ea0d17785d2e9f56b778 [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) {
Rui Ueyama170a1a82013-12-20 07:48:29 +000073 llvm::dbgs() << " " << atomToDebugString(ref->target()) << "\n";
Rui Ueyamaa930d122013-12-09 00:37:19 +000074 }
75 atom = followOnNexts[atom];
76 } while (atom != start);
77 llvm::report_fatal_error("Cycle detected");
78}
79
80/// Exit if there's a cycle in a followon chain reachable from the
81/// given root atom. Uses the tortoise and hare algorithm to detect a
82/// cycle.
83static void checkNoCycleInFollowonChain(AtomToAtomT &followOnNexts,
84 const DefinedAtom *root) {
85 const DefinedAtom *tortoise = root;
86 const DefinedAtom *hare = followOnNexts[root];
87 while (true) {
88 if (!tortoise || !hare)
89 return;
90 if (tortoise == hare)
91 showCycleDetectedError(followOnNexts, tortoise);
92 tortoise = followOnNexts[tortoise];
93 hare = followOnNexts[followOnNexts[hare]];
94 }
95}
96
97static void checkReachabilityFromRoot(AtomToAtomT &followOnRoots,
98 const DefinedAtom *atom) {
99 if (!atom) return;
100 auto i = followOnRoots.find(atom);
101 if (i == followOnRoots.end()) {
102 Twine msg(Twine("Atom <") + atomToDebugString(atom)
103 + "> has no follow-on root!");
104 llvm_unreachable(msg.str().c_str());
105 }
106 const DefinedAtom *ap = i->second;
107 while (true) {
108 const DefinedAtom *next = followOnRoots[ap];
109 if (!next) {
110 Twine msg(Twine("Atom <" + atomToDebugString(atom)
111 + "> is not reachable from its root!"));
112 llvm_unreachable(msg.str().c_str());
113 }
114 if (next == ap)
115 return;
116 ap = next;
117 }
118}
119
120static void printDefinedAtoms(const MutableFile::DefinedAtomRange &atomRange) {
121 for (const DefinedAtom *atom : atomRange) {
122 llvm::dbgs() << " file=" << atom->file().path()
123 << ", name=" << atom->name()
124 << ", size=" << atom->size()
125 << ", type=" << atom->contentType()
126 << ", ordinal=" << atom->ordinal()
127 << "\n";
128 }
129}
130
131/// Verify that the followon chain is sane. Should not be called in
132/// release binary.
133void LayoutPass::checkFollowonChain(MutableFile::DefinedAtomRange &range) {
134 ScopedTask task(getDefaultDomain(), "LayoutPass::checkFollowonChain");
135
136 // Verify that there's no cycle in follow-on chain.
137 std::set<const DefinedAtom *> roots;
138 for (const auto &ai : _followOnRoots)
139 roots.insert(ai.second);
140 for (const DefinedAtom *root : roots)
141 checkNoCycleInFollowonChain(_followOnNexts, root);
142
143 // Verify that all the atoms in followOnNexts have references to
144 // their roots.
145 for (const auto &ai : _followOnNexts) {
146 checkReachabilityFromRoot(_followOnRoots, ai.first);
147 checkReachabilityFromRoot(_followOnRoots, ai.second);
148 }
149}
Rui Ueyama2994f6f2013-12-08 03:37:58 +0000150#endif // #ifndef NDEBUG
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000151
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000152/// The function compares atoms by sorting atoms in the following order
Shankar Easwarand6d1b522013-09-12 15:59:34 +0000153/// a) Sorts atoms by Section position preference
154/// b) Sorts atoms by their ordinal overrides
155/// (layout-after/layout-before/ingroup)
156/// c) Sorts atoms by their permissions
157/// d) Sorts atoms by their content
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000158/// e) Sorts atoms on how they appear using File Ordinality
159/// f) Sorts atoms on how they appear within the File
Rui Ueyama5af46222013-12-08 03:24:09 +0000160static bool compareAtomsSub(const LayoutPass::SortKey &lc,
161 const LayoutPass::SortKey &rc,
162 std::string &reason) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000163 const DefinedAtom *left = lc._atom;
164 const DefinedAtom *right = rc._atom;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000165 if (left == right) {
166 reason = "same";
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000167 return false;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000168 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000169
Shankar Easwarand8da9892013-05-22 17:41:04 +0000170 // Sort by section position preference.
171 DefinedAtom::SectionPosition leftPos = left->sectionPosition();
172 DefinedAtom::SectionPosition rightPos = right->sectionPosition();
173
Shankar Easwarand8da9892013-05-22 17:41:04 +0000174 bool leftSpecialPos = (leftPos != DefinedAtom::sectionPositionAny);
175 bool rightSpecialPos = (rightPos != DefinedAtom::sectionPositionAny);
176 if (leftSpecialPos || rightSpecialPos) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000177 if (leftPos != rightPos) {
178 DEBUG(reason = formatReason("sectionPos", (int)leftPos, (int)rightPos));
Shankar Easwarand8da9892013-05-22 17:41:04 +0000179 return leftPos < rightPos;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000180 }
Shankar Easwarand8da9892013-05-22 17:41:04 +0000181 }
182
Rui Ueyama46bf8282013-10-19 03:18:18 +0000183 // Find the root of the chain if it is a part of a follow-on chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000184 const DefinedAtom *leftRoot = lc._root;
185 const DefinedAtom *rightRoot = rc._root;
Shankar Easwaranf1b341c2013-09-12 15:43:09 +0000186
187 // Sort atoms by their ordinal overrides only if they fall in the same
188 // chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000189 if (leftRoot == rightRoot) {
190 DEBUG(reason = formatReason("override", lc._override, rc._override));
191 return lc._override < rc._override;
Shankar Easwaran3c5d2c82013-05-10 16:44:02 +0000192 }
193
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000194 // Sort same permissions together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000195 DefinedAtom::ContentPermissions leftPerms = leftRoot->permissions();
196 DefinedAtom::ContentPermissions rightPerms = rightRoot->permissions();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000197
Rui Ueyama6a607b62013-10-18 02:56:31 +0000198 if (leftPerms != rightPerms) {
199 DEBUG(reason =
200 formatReason("contentPerms", (int)leftPerms, (int)rightPerms));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000201 return leftPerms < rightPerms;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000202 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000203
204 // Sort same content types together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000205 DefinedAtom::ContentType leftType = leftRoot->contentType();
206 DefinedAtom::ContentType rightType = rightRoot->contentType();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000207
Rui Ueyama6a607b62013-10-18 02:56:31 +0000208 if (leftType != rightType) {
209 DEBUG(reason = formatReason("contentType", (int)leftType, (int)rightType));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000210 return leftType < rightType;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000211 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000212
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000213 // Sort by .o order.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000214 const File *leftFile = &leftRoot->file();
215 const File *rightFile = &rightRoot->file();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000216
Rui Ueyama6a607b62013-10-18 02:56:31 +0000217 if (leftFile != rightFile) {
218 DEBUG(reason = formatReason(".o order", (int)leftFile->ordinal(),
219 (int)rightFile->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000220 return leftFile->ordinal() < rightFile->ordinal();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000221 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000222
223 // Sort by atom order with .o file.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000224 uint64_t leftOrdinal = leftRoot->ordinal();
225 uint64_t rightOrdinal = rightRoot->ordinal();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000226
Rui Ueyama6a607b62013-10-18 02:56:31 +0000227 if (leftOrdinal != rightOrdinal) {
Rui Ueyama46bf8282013-10-19 03:18:18 +0000228 DEBUG(reason = formatReason("ordinal", (int)leftRoot->ordinal(),
229 (int)rightRoot->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000230 return leftOrdinal < rightOrdinal;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000231 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000232
Rui Ueyamacd480752013-11-27 01:33:42 +0000233 llvm::errs() << "Unordered: <" << left->name() << "> <"
234 << right->name() << ">\n";
Shankar Easwaranbcf36562013-10-11 01:50:04 +0000235 llvm_unreachable("Atoms with Same Ordinal!");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000236}
237
Rui Ueyama5af46222013-12-08 03:24:09 +0000238static bool compareAtoms(const LayoutPass::SortKey &lc,
239 const LayoutPass::SortKey &rc) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000240 std::string reason;
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000241 bool result = compareAtomsSub(lc, rc, reason);
Rui Ueyama6a607b62013-10-18 02:56:31 +0000242 DEBUG({
Rui Ueyama4050b202013-10-18 03:18:52 +0000243 StringRef comp = result ? "<" : ">=";
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000244 llvm::dbgs() << "Layout: '" << lc._atom->name() << "' " << comp << " '"
245 << rc._atom->name() << "' (" << reason << ")\n";
Rui Ueyama6a607b62013-10-18 02:56:31 +0000246 });
247 return result;
248}
249
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000250// Returns the atom immediately followed by the given atom in the followon
251// chain.
252const DefinedAtom *LayoutPass::findAtomFollowedBy(
253 const DefinedAtom *targetAtom) {
254 // Start from the beginning of the chain and follow the chain until
255 // we find the targetChain.
256 const DefinedAtom *atom = _followOnRoots[targetAtom];
257 while (true) {
258 const DefinedAtom *prevAtom = atom;
259 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
260 // The target atom must be in the chain of its root.
261 assert(targetFollowOnAtomsIter != _followOnNexts.end());
262 atom = targetFollowOnAtomsIter->second;
263 if (atom == targetAtom)
264 return prevAtom;
265 }
266}
267
268// Check if all the atoms followed by the given target atom are of size zero.
269// When this method is called, an atom being added is not of size zero and
270// will be added to the head of the followon chain. All the atoms between the
271// atom and the targetAtom (specified by layout-after) need to be of size zero
272// in this case. Otherwise the desired layout is impossible.
273bool LayoutPass::checkAllPrevAtomsZeroSize(const DefinedAtom *targetAtom) {
274 const DefinedAtom *atom = _followOnRoots[targetAtom];
275 while (true) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000276 if (atom == targetAtom)
277 return true;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000278 if (atom->size() != 0)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000279 // TODO: print warning that an impossible layout is being desired by the
280 // user.
281 return false;
Rui Ueyama5ec6d1a2013-05-14 01:51:56 +0000282 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
283 // The target atom must be in the chain of its root.
284 assert(targetFollowOnAtomsIter != _followOnNexts.end());
285 atom = targetFollowOnAtomsIter->second;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000286 }
287}
288
289// Set the root of all atoms in targetAtom's chain to the given root.
290void LayoutPass::setChainRoot(const DefinedAtom *targetAtom,
291 const DefinedAtom *root) {
292 // Walk through the followon chain and override each node's root.
293 while (true) {
294 _followOnRoots[targetAtom] = root;
295 AtomToAtomT::iterator targetFollowOnAtomsIter =
296 _followOnNexts.find(targetAtom);
297 if (targetFollowOnAtomsIter == _followOnNexts.end())
298 return;
299 targetAtom = targetFollowOnAtomsIter->second;
300 }
301}
302
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000303/// This pass builds the followon tables described by two DenseMaps
304/// followOnRoots and followonNexts.
305/// The followOnRoots map contains a mapping of a DefinedAtom to its root
306/// The followOnNexts map contains a mapping of what DefinedAtom follows the
307/// current Atom
308/// The algorithm follows a very simple approach
309/// a) If the atom is first seen, then make that as the root atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000310/// b) The targetAtom which this Atom contains, has the root thats set to the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000311/// root of the current atom
312/// c) If the targetAtom is part of a different tree and the root of the
313/// targetAtom is itself, Chain all the atoms that are contained in the tree
314/// to the current Tree
315/// d) If the targetAtom is part of a different chain and the root of the
316/// targetAtom until the targetAtom has all atoms of size 0, then chain the
317/// targetAtoms and its tree to the current chain
318void LayoutPass::buildFollowOnTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000319 ScopedTask task(getDefaultDomain(), "LayoutPass::buildFollowOnTable");
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000320 // Set the initial size of the followon and the followonNext hash to the
321 // number of atoms that we have.
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000322 _followOnRoots.resize(range.size());
323 _followOnNexts.resize(range.size());
Rui Ueyama0196d1062013-05-14 16:53:59 +0000324 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000325 for (const Reference *r : *ai) {
Nick Kledzike5552772013-12-19 21:58:00 +0000326 if (r->kindNamespace() != lld::Reference::KindNamespace::all)
327 continue;
328 if (r->kindValue() != lld::Reference::kindLayoutAfter)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000329 continue;
Rui Ueyamac1800be2013-11-05 01:37:40 +0000330 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000331 _followOnNexts[ai] = targetAtom;
332
Alp Toker22593762013-12-02 01:28:14 +0000333 // If we find a followon for the first time, let's make that atom as the
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000334 // root atom.
335 if (_followOnRoots.count(ai) == 0)
336 _followOnRoots[ai] = ai;
337
338 auto iter = _followOnRoots.find(targetAtom);
339 if (iter == _followOnRoots.end()) {
Alp Toker22593762013-12-02 01:28:14 +0000340 // If the targetAtom is not a root of any chain, let's make the root of
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000341 // the targetAtom to the root of the current chain.
342 _followOnRoots[targetAtom] = _followOnRoots[ai];
343 } else if (iter->second == targetAtom) {
344 // If the targetAtom is the root of a chain, the chain becomes part of
345 // the current chain. Rewrite the subchain's root to the current
346 // chain's root.
347 setChainRoot(targetAtom, _followOnRoots[ai]);
348 } else {
349 // The targetAtom is already a part of a chain. If the current atom is
350 // of size zero, we can insert it in the middle of the chain just
351 // before the target atom, while not breaking other atom's followon
352 // relationships. If it's not, we can only insert the current atom at
353 // the beginning of the chain. All the atoms followed by the target
354 // atom must be of size zero in that case to satisfy the followon
355 // relationships.
Rui Ueyama0196d1062013-05-14 16:53:59 +0000356 size_t currentAtomSize = ai->size();
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000357 if (currentAtomSize == 0) {
358 const DefinedAtom *targetPrevAtom = findAtomFollowedBy(targetAtom);
359 _followOnNexts[targetPrevAtom] = ai;
360 _followOnRoots[ai] = _followOnRoots[targetPrevAtom];
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000361 } else {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000362 if (!checkAllPrevAtomsZeroSize(targetAtom))
363 break;
364 _followOnNexts[ai] = _followOnRoots[targetAtom];
365 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
366 }
367 }
368 }
369 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000370}
371
372/// This pass builds the followon tables using InGroup relationships
373/// The algorithm follows a very simple approach
374/// a) If the rootAtom is not part of any root, create a new root with the
375/// as the head
376/// b) If the current Atom root is not found, then make the current atoms root
377/// point to the rootAtom
378/// c) If the root of the current Atom is itself a root of some other tree
379/// make all the atoms in the chain point to the ingroup reference
380/// d) Check to see if the current atom is part of the chain from the rootAtom
381/// if not add the atom to the chain, so that the current atom is part of the
382/// the chain where the rootAtom is in
383void LayoutPass::buildInGroupTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000384 ScopedTask task(getDefaultDomain(), "LayoutPass::buildInGroupTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000385 // This table would convert precededby references to follow on
386 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000387 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000388 for (const Reference *r : *ai) {
Nick Kledzike5552772013-12-19 21:58:00 +0000389 if (r->kindNamespace() != lld::Reference::KindNamespace::all)
390 continue;
391 if (r->kindValue() == lld::Reference::kindInGroup) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000392 const DefinedAtom *rootAtom = dyn_cast<DefinedAtom>(r->target());
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000393 // If the root atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000394 // create a new root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000395 if (_followOnRoots.count(rootAtom) == 0) {
396 _followOnRoots[rootAtom] = rootAtom;
397 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000398 // If the current Atom has not been seen yet and there is no root
399 // that has been set, set the root of the atom to the targetAtom
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000400 // as the targetAtom points to the ingroup root
401 auto iter = _followOnRoots.find(ai);
402 if (iter == _followOnRoots.end()) {
403 _followOnRoots[ai] = rootAtom;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000404 } else if (iter->second == ai) {
405 if (iter->second != rootAtom)
406 setChainRoot(iter->second, rootAtom);
407 } else {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000408 // TODO : Flag an error that the root of the tree
409 // is different, Here is an example
410 // Say there are atoms
411 // chain 1 : a->b->c
412 // chain 2 : d->e->f
413 // and e,f have their ingroup reference as a
414 // this could happen only if the root of e,f that is d
415 // has root as 'a'
416 continue;
417 }
418
419 // Check if the current atom is part of the chain
420 bool isAtomInChain = false;
421 const DefinedAtom *lastAtom = rootAtom;
Rui Ueyamac53b3b02013-12-10 06:19:09 +0000422 for (;;) {
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000423 AtomToAtomT::iterator followOnAtomsIter =
Rui Ueyamac53b3b02013-12-10 06:19:09 +0000424 _followOnNexts.find(lastAtom);
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000425 if (followOnAtomsIter != _followOnNexts.end()) {
426 lastAtom = followOnAtomsIter->second;
Rui Ueyamac53b3b02013-12-10 06:19:09 +0000427 if (lastAtom != ai)
428 continue;
429 isAtomInChain = true;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000430 }
Rui Ueyamac53b3b02013-12-10 06:19:09 +0000431 break;
432 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000433
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000434 if (!isAtomInChain)
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000435 _followOnNexts[lastAtom] = ai;
436 }
437 }
438 }
439}
440
441/// This pass builds the followon tables using Preceded By relationships
442/// The algorithm follows a very simple approach
443/// a) If the targetAtom is not part of any root and the current atom is not
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000444/// part of any root, create a chain with the current atom as root and
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000445/// the targetAtom as following the current atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000446/// b) Chain the targetAtom to the current Atom if the targetAtom is not part
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000447/// of any chain and the currentAtom has no followOn's
448/// c) If the targetAtom is part of a different tree and the root of the
449/// targetAtom is itself, and if the current atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000450/// chain all the atoms together
451/// d) If the current atom has no followon and the root of the targetAtom is
452/// not equal to the root of the current atom(the targetAtom is not in the
453/// same chain), chain all the atoms that are lead by the targetAtom into
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000454/// the current chain
455void LayoutPass::buildPrecededByTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000456 ScopedTask task(getDefaultDomain(), "LayoutPass::buildPrecededByTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000457 // This table would convert precededby references to follow on
458 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000459 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000460 for (const Reference *r : *ai) {
Nick Kledzike5552772013-12-19 21:58:00 +0000461 if (r->kindNamespace() != lld::Reference::KindNamespace::all)
462 continue;
463 if (r->kindValue() == lld::Reference::kindLayoutBefore) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000464 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000465 // Is the targetAtom not chained
466 if (_followOnRoots.count(targetAtom) == 0) {
467 // Is the current atom not part of any root ?
468 if (_followOnRoots.count(ai) == 0) {
469 _followOnRoots[ai] = ai;
470 _followOnNexts[ai] = targetAtom;
471 _followOnRoots[targetAtom] = _followOnRoots[ai];
472 } else if (_followOnNexts.count(ai) == 0) {
473 // Chain the targetAtom to the current Atom
474 // if the currentAtom has no followon references
475 _followOnNexts[ai] = targetAtom;
476 _followOnRoots[targetAtom] = _followOnRoots[ai];
477 }
478 } else if (_followOnRoots.find(targetAtom)->second == targetAtom) {
479 // Is the targetAtom in chain with the targetAtom as the root ?
480 bool changeRoots = false;
481 if (_followOnRoots.count(ai) == 0) {
482 _followOnRoots[ai] = ai;
483 _followOnNexts[ai] = targetAtom;
484 _followOnRoots[targetAtom] = _followOnRoots[ai];
485 changeRoots = true;
486 } else if (_followOnNexts.count(ai) == 0) {
487 // Chain the targetAtom to the current Atom
488 // if the currentAtom has no followon references
489 if (_followOnRoots[ai] != _followOnRoots[targetAtom]) {
490 _followOnNexts[ai] = targetAtom;
491 _followOnRoots[targetAtom] = _followOnRoots[ai];
492 changeRoots = true;
493 }
494 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000495 // Change the roots of the targetAtom and its chain to
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000496 // the current atoms root
497 if (changeRoots) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000498 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
499 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000500 } // Is targetAtom root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000501 } // kindLayoutBefore
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000502 } // Reference
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000503 } // atom iteration
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000504} // end function
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000505
506
507/// Build an ordinal override map by traversing the followon chain, and
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000508/// assigning ordinals to each atom, if the atoms have their ordinals
509/// already assigned skip the atom and move to the next. This is the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000510/// main map thats used to sort the atoms while comparing two atoms together
511void LayoutPass::buildOrdinalOverrideMap(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000512 ScopedTask task(getDefaultDomain(), "LayoutPass::buildOrdinalOverrideMap");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000513 uint64_t index = 0;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000514 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000515 const DefinedAtom *atom = ai;
Michael J. Spencer1ecf8902013-03-12 00:10:00 +0000516 if (_ordinalOverrideMap.find(atom) != _ordinalOverrideMap.end())
517 continue;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000518 AtomToAtomT::iterator start = _followOnRoots.find(atom);
519 if (start != _followOnRoots.end()) {
520 for (const DefinedAtom *nextAtom = start->second; nextAtom != NULL;
521 nextAtom = _followOnNexts[nextAtom]) {
522 AtomToOrdinalT::iterator pos = _ordinalOverrideMap.find(nextAtom);
Rui Ueyamac53b3b02013-12-10 06:19:09 +0000523 if (pos == _ordinalOverrideMap.end())
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000524 _ordinalOverrideMap[nextAtom] = index++;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000525 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000526 }
527 }
528}
529
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000530std::vector<LayoutPass::SortKey>
531LayoutPass::decorate(MutableFile::DefinedAtomRange &atomRange) const {
532 std::vector<SortKey> ret;
533 for (const DefinedAtom *atom : atomRange) {
534 auto ri = _followOnRoots.find(atom);
535 auto oi = _ordinalOverrideMap.find(atom);
536 const DefinedAtom *root = (ri == _followOnRoots.end()) ? atom : ri->second;
537 uint64_t override = (oi == _ordinalOverrideMap.end()) ? 0 : oi->second;
538 ret.push_back(SortKey(atom, root, override));
539 }
540 return ret;
541}
542
543void LayoutPass::undecorate(MutableFile::DefinedAtomRange &atomRange,
544 std::vector<SortKey> &keys) const {
545 size_t i = 0;
546 for (SortKey &k : keys)
547 atomRange[i++] = k._atom;
548}
549
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000550/// Perform the actual pass
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000551void LayoutPass::perform(std::unique_ptr<MutableFile> &mergedFile) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000552 // sort the atoms
Michael J. Spencerbd66d042013-05-28 18:55:39 +0000553 ScopedTask task(getDefaultDomain(), "LayoutPass");
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000554 MutableFile::DefinedAtomRange atomRange = mergedFile->definedAtoms();
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000555
556 // Build follow on tables
557 buildFollowOnTable(atomRange);
558
559 // Build Ingroup reference table
560 buildInGroupTable(atomRange);
561
562 // Build preceded by tables
563 buildPrecededByTable(atomRange);
564
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000565 // Check the structure of followon graph if running in debug mode.
566 DEBUG(checkFollowonChain(atomRange));
567
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000568 // Build override maps
569 buildOrdinalOverrideMap(atomRange);
570
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000571 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000572 llvm::dbgs() << "unsorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000573 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000574 });
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000575
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000576 std::vector<LayoutPass::SortKey> vec = decorate(atomRange);
577 std::sort(vec.begin(), vec.end(), compareAtoms);
578 DEBUG(checkTransitivity(vec));
579 undecorate(atomRange, vec);
Rui Ueyama46bf8282013-10-19 03:18:18 +0000580
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000581 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000582 llvm::dbgs() << "sorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000583 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000584 });
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000585}