blob: a98fb8ab664de7dc2dbf5fee0edd0e555bc7c894 [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
Nico Rieckb9d84f42014-02-24 21:14:37 +000066static void showCycleDetectedError(const Registry &registry,
67 AtomToAtomT &followOnNexts,
Rui Ueyamaa930d122013-12-09 00:37:19 +000068 const DefinedAtom *atom) {
69 const DefinedAtom *start = atom;
70 llvm::dbgs() << "There's a cycle in a follow-on chain!\n";
71 do {
72 llvm::dbgs() << " " << atomToDebugString(atom) << "\n";
73 for (const Reference *ref : *atom) {
Nico Rieckb9d84f42014-02-24 21:14:37 +000074 StringRef kindValStr;
75 if (!registry.referenceKindToString(ref->kindNamespace(), ref->kindArch(),
76 ref->kindValue(), kindValStr)) {
77 kindValStr = "<unknown>";
78 }
79 llvm::dbgs() << " " << kindValStr
80 << ": " << atomToDebugString(ref->target()) << "\n";
Rui Ueyamaa930d122013-12-09 00:37:19 +000081 }
82 atom = followOnNexts[atom];
83 } while (atom != start);
84 llvm::report_fatal_error("Cycle detected");
85}
86
87/// Exit if there's a cycle in a followon chain reachable from the
88/// given root atom. Uses the tortoise and hare algorithm to detect a
89/// cycle.
Nico Rieckb9d84f42014-02-24 21:14:37 +000090static void checkNoCycleInFollowonChain(const Registry &registry,
91 AtomToAtomT &followOnNexts,
Rui Ueyamaa930d122013-12-09 00:37:19 +000092 const DefinedAtom *root) {
93 const DefinedAtom *tortoise = root;
94 const DefinedAtom *hare = followOnNexts[root];
95 while (true) {
96 if (!tortoise || !hare)
97 return;
98 if (tortoise == hare)
Nico Rieckb9d84f42014-02-24 21:14:37 +000099 showCycleDetectedError(registry, followOnNexts, tortoise);
Rui Ueyamaa930d122013-12-09 00:37:19 +0000100 tortoise = followOnNexts[tortoise];
101 hare = followOnNexts[followOnNexts[hare]];
102 }
103}
104
105static void checkReachabilityFromRoot(AtomToAtomT &followOnRoots,
106 const DefinedAtom *atom) {
107 if (!atom) return;
108 auto i = followOnRoots.find(atom);
109 if (i == followOnRoots.end()) {
110 Twine msg(Twine("Atom <") + atomToDebugString(atom)
111 + "> has no follow-on root!");
112 llvm_unreachable(msg.str().c_str());
113 }
114 const DefinedAtom *ap = i->second;
115 while (true) {
116 const DefinedAtom *next = followOnRoots[ap];
117 if (!next) {
118 Twine msg(Twine("Atom <" + atomToDebugString(atom)
119 + "> is not reachable from its root!"));
120 llvm_unreachable(msg.str().c_str());
121 }
122 if (next == ap)
123 return;
124 ap = next;
125 }
126}
127
128static void printDefinedAtoms(const MutableFile::DefinedAtomRange &atomRange) {
129 for (const DefinedAtom *atom : atomRange) {
130 llvm::dbgs() << " file=" << atom->file().path()
131 << ", name=" << atom->name()
132 << ", size=" << atom->size()
133 << ", type=" << atom->contentType()
134 << ", ordinal=" << atom->ordinal()
135 << "\n";
136 }
137}
138
139/// Verify that the followon chain is sane. Should not be called in
140/// release binary.
141void LayoutPass::checkFollowonChain(MutableFile::DefinedAtomRange &range) {
142 ScopedTask task(getDefaultDomain(), "LayoutPass::checkFollowonChain");
143
144 // Verify that there's no cycle in follow-on chain.
145 std::set<const DefinedAtom *> roots;
146 for (const auto &ai : _followOnRoots)
147 roots.insert(ai.second);
148 for (const DefinedAtom *root : roots)
Nico Rieckb9d84f42014-02-24 21:14:37 +0000149 checkNoCycleInFollowonChain(_registry, _followOnNexts, root);
Rui Ueyamaa930d122013-12-09 00:37:19 +0000150
151 // Verify that all the atoms in followOnNexts have references to
152 // their roots.
153 for (const auto &ai : _followOnNexts) {
154 checkReachabilityFromRoot(_followOnRoots, ai.first);
155 checkReachabilityFromRoot(_followOnRoots, ai.second);
156 }
157}
Rui Ueyama2994f6f2013-12-08 03:37:58 +0000158#endif // #ifndef NDEBUG
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000159
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000160/// The function compares atoms by sorting atoms in the following order
Shankar Easwarand6d1b522013-09-12 15:59:34 +0000161/// a) Sorts atoms by Section position preference
162/// b) Sorts atoms by their ordinal overrides
163/// (layout-after/layout-before/ingroup)
164/// c) Sorts atoms by their permissions
165/// d) Sorts atoms by their content
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000166/// e) Sorts atoms on how they appear using File Ordinality
167/// f) Sorts atoms on how they appear within the File
Rui Ueyama5af46222013-12-08 03:24:09 +0000168static bool compareAtomsSub(const LayoutPass::SortKey &lc,
169 const LayoutPass::SortKey &rc,
170 std::string &reason) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000171 const DefinedAtom *left = lc._atom;
172 const DefinedAtom *right = rc._atom;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000173 if (left == right) {
174 reason = "same";
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000175 return false;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000176 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000177
Shankar Easwarand8da9892013-05-22 17:41:04 +0000178 // Sort by section position preference.
179 DefinedAtom::SectionPosition leftPos = left->sectionPosition();
180 DefinedAtom::SectionPosition rightPos = right->sectionPosition();
181
Shankar Easwarand8da9892013-05-22 17:41:04 +0000182 bool leftSpecialPos = (leftPos != DefinedAtom::sectionPositionAny);
183 bool rightSpecialPos = (rightPos != DefinedAtom::sectionPositionAny);
184 if (leftSpecialPos || rightSpecialPos) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000185 if (leftPos != rightPos) {
186 DEBUG(reason = formatReason("sectionPos", (int)leftPos, (int)rightPos));
Shankar Easwarand8da9892013-05-22 17:41:04 +0000187 return leftPos < rightPos;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000188 }
Shankar Easwarand8da9892013-05-22 17:41:04 +0000189 }
190
Rui Ueyama46bf8282013-10-19 03:18:18 +0000191 // Find the root of the chain if it is a part of a follow-on chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000192 const DefinedAtom *leftRoot = lc._root;
193 const DefinedAtom *rightRoot = rc._root;
Shankar Easwaranf1b341c2013-09-12 15:43:09 +0000194
195 // Sort atoms by their ordinal overrides only if they fall in the same
196 // chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000197 if (leftRoot == rightRoot) {
198 DEBUG(reason = formatReason("override", lc._override, rc._override));
199 return lc._override < rc._override;
Shankar Easwaran3c5d2c82013-05-10 16:44:02 +0000200 }
201
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000202 // Sort same permissions together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000203 DefinedAtom::ContentPermissions leftPerms = leftRoot->permissions();
204 DefinedAtom::ContentPermissions rightPerms = rightRoot->permissions();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000205
Rui Ueyama6a607b62013-10-18 02:56:31 +0000206 if (leftPerms != rightPerms) {
207 DEBUG(reason =
208 formatReason("contentPerms", (int)leftPerms, (int)rightPerms));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000209 return leftPerms < rightPerms;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000210 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000211
212 // Sort same content types together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000213 DefinedAtom::ContentType leftType = leftRoot->contentType();
214 DefinedAtom::ContentType rightType = rightRoot->contentType();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000215
Rui Ueyama6a607b62013-10-18 02:56:31 +0000216 if (leftType != rightType) {
217 DEBUG(reason = formatReason("contentType", (int)leftType, (int)rightType));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000218 return leftType < rightType;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000219 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000220
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000221 // Sort by .o order.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000222 const File *leftFile = &leftRoot->file();
223 const File *rightFile = &rightRoot->file();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000224
Rui Ueyama6a607b62013-10-18 02:56:31 +0000225 if (leftFile != rightFile) {
226 DEBUG(reason = formatReason(".o order", (int)leftFile->ordinal(),
227 (int)rightFile->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000228 return leftFile->ordinal() < rightFile->ordinal();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000229 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000230
231 // Sort by atom order with .o file.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000232 uint64_t leftOrdinal = leftRoot->ordinal();
233 uint64_t rightOrdinal = rightRoot->ordinal();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000234
Rui Ueyama6a607b62013-10-18 02:56:31 +0000235 if (leftOrdinal != rightOrdinal) {
Rui Ueyama46bf8282013-10-19 03:18:18 +0000236 DEBUG(reason = formatReason("ordinal", (int)leftRoot->ordinal(),
237 (int)rightRoot->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000238 return leftOrdinal < rightOrdinal;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000239 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000240
Rui Ueyamacd480752013-11-27 01:33:42 +0000241 llvm::errs() << "Unordered: <" << left->name() << "> <"
242 << right->name() << ">\n";
Shankar Easwaranbcf36562013-10-11 01:50:04 +0000243 llvm_unreachable("Atoms with Same Ordinal!");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000244}
245
Rui Ueyama5af46222013-12-08 03:24:09 +0000246static bool compareAtoms(const LayoutPass::SortKey &lc,
247 const LayoutPass::SortKey &rc) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000248 std::string reason;
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000249 bool result = compareAtomsSub(lc, rc, reason);
Rui Ueyama6a607b62013-10-18 02:56:31 +0000250 DEBUG({
Rui Ueyama4050b202013-10-18 03:18:52 +0000251 StringRef comp = result ? "<" : ">=";
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000252 llvm::dbgs() << "Layout: '" << lc._atom->name() << "' " << comp << " '"
253 << rc._atom->name() << "' (" << reason << ")\n";
Rui Ueyama6a607b62013-10-18 02:56:31 +0000254 });
255 return result;
256}
257
Nico Rieckb9d84f42014-02-24 21:14:37 +0000258LayoutPass::LayoutPass(const Registry &registry) : _registry(registry) {}
259
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000260// Returns the atom immediately followed by the given atom in the followon
261// chain.
262const DefinedAtom *LayoutPass::findAtomFollowedBy(
263 const DefinedAtom *targetAtom) {
264 // Start from the beginning of the chain and follow the chain until
265 // we find the targetChain.
266 const DefinedAtom *atom = _followOnRoots[targetAtom];
267 while (true) {
268 const DefinedAtom *prevAtom = atom;
269 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
270 // The target atom must be in the chain of its root.
271 assert(targetFollowOnAtomsIter != _followOnNexts.end());
272 atom = targetFollowOnAtomsIter->second;
273 if (atom == targetAtom)
274 return prevAtom;
275 }
276}
277
278// Check if all the atoms followed by the given target atom are of size zero.
279// When this method is called, an atom being added is not of size zero and
280// will be added to the head of the followon chain. All the atoms between the
281// atom and the targetAtom (specified by layout-after) need to be of size zero
282// in this case. Otherwise the desired layout is impossible.
283bool LayoutPass::checkAllPrevAtomsZeroSize(const DefinedAtom *targetAtom) {
284 const DefinedAtom *atom = _followOnRoots[targetAtom];
285 while (true) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000286 if (atom == targetAtom)
287 return true;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000288 if (atom->size() != 0)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000289 // TODO: print warning that an impossible layout is being desired by the
290 // user.
291 return false;
Rui Ueyama5ec6d1a2013-05-14 01:51:56 +0000292 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
293 // The target atom must be in the chain of its root.
294 assert(targetFollowOnAtomsIter != _followOnNexts.end());
295 atom = targetFollowOnAtomsIter->second;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000296 }
297}
298
299// Set the root of all atoms in targetAtom's chain to the given root.
300void LayoutPass::setChainRoot(const DefinedAtom *targetAtom,
301 const DefinedAtom *root) {
302 // Walk through the followon chain and override each node's root.
303 while (true) {
304 _followOnRoots[targetAtom] = root;
305 AtomToAtomT::iterator targetFollowOnAtomsIter =
306 _followOnNexts.find(targetAtom);
307 if (targetFollowOnAtomsIter == _followOnNexts.end())
308 return;
309 targetAtom = targetFollowOnAtomsIter->second;
310 }
311}
312
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000313/// This pass builds the followon tables described by two DenseMaps
314/// followOnRoots and followonNexts.
315/// The followOnRoots map contains a mapping of a DefinedAtom to its root
316/// The followOnNexts map contains a mapping of what DefinedAtom follows the
317/// current Atom
318/// The algorithm follows a very simple approach
319/// a) If the atom is first seen, then make that as the root atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000320/// b) The targetAtom which this Atom contains, has the root thats set to the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000321/// root of the current atom
322/// c) If the targetAtom is part of a different tree and the root of the
323/// targetAtom is itself, Chain all the atoms that are contained in the tree
324/// to the current Tree
325/// d) If the targetAtom is part of a different chain and the root of the
326/// targetAtom until the targetAtom has all atoms of size 0, then chain the
327/// targetAtoms and its tree to the current chain
328void LayoutPass::buildFollowOnTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000329 ScopedTask task(getDefaultDomain(), "LayoutPass::buildFollowOnTable");
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000330 // Set the initial size of the followon and the followonNext hash to the
331 // number of atoms that we have.
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000332 _followOnRoots.resize(range.size());
333 _followOnNexts.resize(range.size());
Rui Ueyama0196d1062013-05-14 16:53:59 +0000334 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000335 for (const Reference *r : *ai) {
Nick Kledzike5552772013-12-19 21:58:00 +0000336 if (r->kindNamespace() != lld::Reference::KindNamespace::all)
337 continue;
338 if (r->kindValue() != lld::Reference::kindLayoutAfter)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000339 continue;
Rui Ueyamac1800be2013-11-05 01:37:40 +0000340 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000341 _followOnNexts[ai] = targetAtom;
342
Alp Toker22593762013-12-02 01:28:14 +0000343 // If we find a followon for the first time, let's make that atom as the
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000344 // root atom.
345 if (_followOnRoots.count(ai) == 0)
346 _followOnRoots[ai] = ai;
347
348 auto iter = _followOnRoots.find(targetAtom);
349 if (iter == _followOnRoots.end()) {
Alp Toker22593762013-12-02 01:28:14 +0000350 // If the targetAtom is not a root of any chain, let's make the root of
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000351 // the targetAtom to the root of the current chain.
352 _followOnRoots[targetAtom] = _followOnRoots[ai];
353 } else if (iter->second == targetAtom) {
354 // If the targetAtom is the root of a chain, the chain becomes part of
355 // the current chain. Rewrite the subchain's root to the current
356 // chain's root.
357 setChainRoot(targetAtom, _followOnRoots[ai]);
358 } else {
359 // The targetAtom is already a part of a chain. If the current atom is
360 // of size zero, we can insert it in the middle of the chain just
361 // before the target atom, while not breaking other atom's followon
362 // relationships. If it's not, we can only insert the current atom at
363 // the beginning of the chain. All the atoms followed by the target
364 // atom must be of size zero in that case to satisfy the followon
365 // relationships.
Rui Ueyama0196d1062013-05-14 16:53:59 +0000366 size_t currentAtomSize = ai->size();
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000367 if (currentAtomSize == 0) {
368 const DefinedAtom *targetPrevAtom = findAtomFollowedBy(targetAtom);
369 _followOnNexts[targetPrevAtom] = ai;
370 _followOnRoots[ai] = _followOnRoots[targetPrevAtom];
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000371 } else {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000372 if (!checkAllPrevAtomsZeroSize(targetAtom))
373 break;
374 _followOnNexts[ai] = _followOnRoots[targetAtom];
375 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
376 }
377 }
378 }
379 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000380}
381
382/// This pass builds the followon tables using InGroup relationships
383/// The algorithm follows a very simple approach
384/// a) If the rootAtom is not part of any root, create a new root with the
385/// as the head
386/// b) If the current Atom root is not found, then make the current atoms root
387/// point to the rootAtom
388/// c) If the root of the current Atom is itself a root of some other tree
389/// make all the atoms in the chain point to the ingroup reference
390/// d) Check to see if the current atom is part of the chain from the rootAtom
391/// if not add the atom to the chain, so that the current atom is part of the
392/// the chain where the rootAtom is in
393void LayoutPass::buildInGroupTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000394 ScopedTask task(getDefaultDomain(), "LayoutPass::buildInGroupTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000395 // This table would convert precededby references to follow on
396 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000397 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000398 for (const Reference *r : *ai) {
Nick Kledzike5552772013-12-19 21:58:00 +0000399 if (r->kindNamespace() != lld::Reference::KindNamespace::all)
400 continue;
401 if (r->kindValue() == lld::Reference::kindInGroup) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000402 const DefinedAtom *rootAtom = dyn_cast<DefinedAtom>(r->target());
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000403 // If the root atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000404 // create a new root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000405 if (_followOnRoots.count(rootAtom) == 0) {
406 _followOnRoots[rootAtom] = rootAtom;
407 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000408 // If the current Atom has not been seen yet and there is no root
409 // that has been set, set the root of the atom to the targetAtom
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000410 // as the targetAtom points to the ingroup root
411 auto iter = _followOnRoots.find(ai);
412 if (iter == _followOnRoots.end()) {
413 _followOnRoots[ai] = rootAtom;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000414 } else if (iter->second == ai) {
415 if (iter->second != rootAtom)
416 setChainRoot(iter->second, rootAtom);
417 } else {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000418 // TODO : Flag an error that the root of the tree
419 // is different, Here is an example
420 // Say there are atoms
421 // chain 1 : a->b->c
422 // chain 2 : d->e->f
423 // and e,f have their ingroup reference as a
424 // this could happen only if the root of e,f that is d
425 // has root as 'a'
426 continue;
427 }
428
429 // Check if the current atom is part of the chain
430 bool isAtomInChain = false;
431 const DefinedAtom *lastAtom = rootAtom;
Rui Ueyamac53b3b02013-12-10 06:19:09 +0000432 for (;;) {
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000433 AtomToAtomT::iterator followOnAtomsIter =
Rui Ueyamac53b3b02013-12-10 06:19:09 +0000434 _followOnNexts.find(lastAtom);
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000435 if (followOnAtomsIter != _followOnNexts.end()) {
436 lastAtom = followOnAtomsIter->second;
Rui Ueyamac53b3b02013-12-10 06:19:09 +0000437 if (lastAtom != ai)
438 continue;
439 isAtomInChain = true;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000440 }
Rui Ueyamac53b3b02013-12-10 06:19:09 +0000441 break;
442 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000443
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000444 if (!isAtomInChain)
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000445 _followOnNexts[lastAtom] = ai;
446 }
447 }
448 }
449}
450
451/// This pass builds the followon tables using Preceded By relationships
452/// The algorithm follows a very simple approach
453/// a) If the targetAtom is not part of any root and the current atom is not
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000454/// part of any root, create a chain with the current atom as root and
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000455/// the targetAtom as following the current atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000456/// b) Chain the targetAtom to the current Atom if the targetAtom is not part
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000457/// of any chain and the currentAtom has no followOn's
458/// c) If the targetAtom is part of a different tree and the root of the
459/// targetAtom is itself, and if the current atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000460/// chain all the atoms together
461/// d) If the current atom has no followon and the root of the targetAtom is
462/// not equal to the root of the current atom(the targetAtom is not in the
463/// same chain), chain all the atoms that are lead by the targetAtom into
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000464/// the current chain
465void LayoutPass::buildPrecededByTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000466 ScopedTask task(getDefaultDomain(), "LayoutPass::buildPrecededByTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000467 // This table would convert precededby references to follow on
468 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000469 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000470 for (const Reference *r : *ai) {
Nick Kledzike5552772013-12-19 21:58:00 +0000471 if (r->kindNamespace() != lld::Reference::KindNamespace::all)
472 continue;
473 if (r->kindValue() == lld::Reference::kindLayoutBefore) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000474 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000475 // Is the targetAtom not chained
476 if (_followOnRoots.count(targetAtom) == 0) {
477 // Is the current atom not part of any root ?
478 if (_followOnRoots.count(ai) == 0) {
479 _followOnRoots[ai] = ai;
480 _followOnNexts[ai] = targetAtom;
481 _followOnRoots[targetAtom] = _followOnRoots[ai];
482 } else if (_followOnNexts.count(ai) == 0) {
483 // Chain the targetAtom to the current Atom
484 // if the currentAtom has no followon references
485 _followOnNexts[ai] = targetAtom;
486 _followOnRoots[targetAtom] = _followOnRoots[ai];
487 }
488 } else if (_followOnRoots.find(targetAtom)->second == targetAtom) {
489 // Is the targetAtom in chain with the targetAtom as the root ?
490 bool changeRoots = false;
491 if (_followOnRoots.count(ai) == 0) {
492 _followOnRoots[ai] = ai;
493 _followOnNexts[ai] = targetAtom;
494 _followOnRoots[targetAtom] = _followOnRoots[ai];
495 changeRoots = true;
496 } else if (_followOnNexts.count(ai) == 0) {
497 // Chain the targetAtom to the current Atom
498 // if the currentAtom has no followon references
499 if (_followOnRoots[ai] != _followOnRoots[targetAtom]) {
500 _followOnNexts[ai] = targetAtom;
501 _followOnRoots[targetAtom] = _followOnRoots[ai];
502 changeRoots = true;
503 }
504 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000505 // Change the roots of the targetAtom and its chain to
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000506 // the current atoms root
507 if (changeRoots) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000508 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
509 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000510 } // Is targetAtom root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000511 } // kindLayoutBefore
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000512 } // Reference
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000513 } // atom iteration
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000514} // end function
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000515
516
517/// Build an ordinal override map by traversing the followon chain, and
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000518/// assigning ordinals to each atom, if the atoms have their ordinals
519/// already assigned skip the atom and move to the next. This is the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000520/// main map thats used to sort the atoms while comparing two atoms together
521void LayoutPass::buildOrdinalOverrideMap(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000522 ScopedTask task(getDefaultDomain(), "LayoutPass::buildOrdinalOverrideMap");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000523 uint64_t index = 0;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000524 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000525 const DefinedAtom *atom = ai;
Michael J. Spencer1ecf8902013-03-12 00:10:00 +0000526 if (_ordinalOverrideMap.find(atom) != _ordinalOverrideMap.end())
527 continue;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000528 AtomToAtomT::iterator start = _followOnRoots.find(atom);
529 if (start != _followOnRoots.end()) {
530 for (const DefinedAtom *nextAtom = start->second; nextAtom != NULL;
531 nextAtom = _followOnNexts[nextAtom]) {
532 AtomToOrdinalT::iterator pos = _ordinalOverrideMap.find(nextAtom);
Rui Ueyamac53b3b02013-12-10 06:19:09 +0000533 if (pos == _ordinalOverrideMap.end())
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000534 _ordinalOverrideMap[nextAtom] = index++;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000535 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000536 }
537 }
538}
539
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000540std::vector<LayoutPass::SortKey>
541LayoutPass::decorate(MutableFile::DefinedAtomRange &atomRange) const {
542 std::vector<SortKey> ret;
543 for (const DefinedAtom *atom : atomRange) {
544 auto ri = _followOnRoots.find(atom);
545 auto oi = _ordinalOverrideMap.find(atom);
546 const DefinedAtom *root = (ri == _followOnRoots.end()) ? atom : ri->second;
547 uint64_t override = (oi == _ordinalOverrideMap.end()) ? 0 : oi->second;
548 ret.push_back(SortKey(atom, root, override));
549 }
550 return ret;
551}
552
553void LayoutPass::undecorate(MutableFile::DefinedAtomRange &atomRange,
554 std::vector<SortKey> &keys) const {
555 size_t i = 0;
556 for (SortKey &k : keys)
557 atomRange[i++] = k._atom;
558}
559
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000560/// Perform the actual pass
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000561void LayoutPass::perform(std::unique_ptr<MutableFile> &mergedFile) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000562 // sort the atoms
Michael J. Spencerbd66d042013-05-28 18:55:39 +0000563 ScopedTask task(getDefaultDomain(), "LayoutPass");
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000564 MutableFile::DefinedAtomRange atomRange = mergedFile->definedAtoms();
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000565
566 // Build follow on tables
567 buildFollowOnTable(atomRange);
568
569 // Build Ingroup reference table
570 buildInGroupTable(atomRange);
571
572 // Build preceded by tables
573 buildPrecededByTable(atomRange);
574
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000575 // Check the structure of followon graph if running in debug mode.
576 DEBUG(checkFollowonChain(atomRange));
577
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000578 // Build override maps
579 buildOrdinalOverrideMap(atomRange);
580
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000581 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000582 llvm::dbgs() << "unsorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000583 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000584 });
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000585
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000586 std::vector<LayoutPass::SortKey> vec = decorate(atomRange);
587 std::sort(vec.begin(), vec.end(), compareAtoms);
588 DEBUG(checkTransitivity(vec));
589 undecorate(atomRange, vec);
Rui Ueyama46bf8282013-10-19 03:18:18 +0000590
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000591 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000592 llvm::dbgs() << "sorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000593 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000594 });
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000595}