blob: a8e10126f77d3908eb25ed2ceae49f8a2ee49bb0 [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 Ueyama6a607b62013-10-18 02:56:31 +000026// Return "reason (leftval, rightval)"
Rui Ueyama5af46222013-12-08 03:24:09 +000027static std::string formatReason(StringRef reason, int leftVal, int rightVal) {
Rui Ueyama6a607b62013-10-18 02:56:31 +000028 Twine msg =
29 Twine(reason) + " (" + Twine(leftVal) + ", " + Twine(rightVal) + ")";
Rui Ueyamac74157c2013-11-01 20:40:33 +000030 return msg.str();
Rui Ueyama6a607b62013-10-18 02:56:31 +000031}
Rui Ueyama46bf8282013-10-19 03:18:18 +000032
33// Less-than relationship of two atoms must be transitive, which is, if a < b
34// and b < c, a < c must be true. This function checks the transitivity by
35// checking the sort results.
Rui Ueyama5af46222013-12-08 03:24:09 +000036static void checkTransitivity(std::vector<LayoutPass::SortKey> &vec) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000037 for (auto i = vec.begin(), e = vec.end(); (i + 1) != e; ++i) {
38 for (auto j = i + 1; j != e; ++j) {
39 assert(compareAtoms(*i, *j));
40 assert(!compareAtoms(*j, *i));
Rui Ueyama46bf8282013-10-19 03:18:18 +000041 }
42 }
Rui Ueyama6a607b62013-10-18 02:56:31 +000043}
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000044
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000045/// The function compares atoms by sorting atoms in the following order
Shankar Easwarand6d1b522013-09-12 15:59:34 +000046/// a) Sorts atoms by Section position preference
47/// b) Sorts atoms by their ordinal overrides
48/// (layout-after/layout-before/ingroup)
49/// c) Sorts atoms by their permissions
50/// d) Sorts atoms by their content
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000051/// e) Sorts atoms on how they appear using File Ordinality
52/// f) Sorts atoms on how they appear within the File
Rui Ueyama5af46222013-12-08 03:24:09 +000053static bool compareAtomsSub(const LayoutPass::SortKey &lc,
54 const LayoutPass::SortKey &rc,
55 std::string &reason) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000056 const DefinedAtom *left = lc._atom;
57 const DefinedAtom *right = rc._atom;
Rui Ueyama6a607b62013-10-18 02:56:31 +000058 if (left == right) {
59 reason = "same";
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000060 return false;
Rui Ueyama6a607b62013-10-18 02:56:31 +000061 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000062
Shankar Easwarand8da9892013-05-22 17:41:04 +000063 // Sort by section position preference.
64 DefinedAtom::SectionPosition leftPos = left->sectionPosition();
65 DefinedAtom::SectionPosition rightPos = right->sectionPosition();
66
Shankar Easwarand8da9892013-05-22 17:41:04 +000067 bool leftSpecialPos = (leftPos != DefinedAtom::sectionPositionAny);
68 bool rightSpecialPos = (rightPos != DefinedAtom::sectionPositionAny);
69 if (leftSpecialPos || rightSpecialPos) {
Rui Ueyama6a607b62013-10-18 02:56:31 +000070 if (leftPos != rightPos) {
71 DEBUG(reason = formatReason("sectionPos", (int)leftPos, (int)rightPos));
Shankar Easwarand8da9892013-05-22 17:41:04 +000072 return leftPos < rightPos;
Rui Ueyama6a607b62013-10-18 02:56:31 +000073 }
Shankar Easwarand8da9892013-05-22 17:41:04 +000074 }
75
Rui Ueyama46bf8282013-10-19 03:18:18 +000076 // Find the root of the chain if it is a part of a follow-on chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000077 const DefinedAtom *leftRoot = lc._root;
78 const DefinedAtom *rightRoot = rc._root;
Shankar Easwaranf1b341c2013-09-12 15:43:09 +000079
80 // Sort atoms by their ordinal overrides only if they fall in the same
81 // chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000082 if (leftRoot == rightRoot) {
83 DEBUG(reason = formatReason("override", lc._override, rc._override));
84 return lc._override < rc._override;
Shankar Easwaran3c5d2c82013-05-10 16:44:02 +000085 }
86
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000087 // Sort same permissions together.
Rui Ueyama46bf8282013-10-19 03:18:18 +000088 DefinedAtom::ContentPermissions leftPerms = leftRoot->permissions();
89 DefinedAtom::ContentPermissions rightPerms = rightRoot->permissions();
Shankar Easwaran8c256852013-03-13 04:05:38 +000090
Rui Ueyama6a607b62013-10-18 02:56:31 +000091 if (leftPerms != rightPerms) {
92 DEBUG(reason =
93 formatReason("contentPerms", (int)leftPerms, (int)rightPerms));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000094 return leftPerms < rightPerms;
Rui Ueyama6a607b62013-10-18 02:56:31 +000095 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000096
97 // Sort same content types together.
Rui Ueyama46bf8282013-10-19 03:18:18 +000098 DefinedAtom::ContentType leftType = leftRoot->contentType();
99 DefinedAtom::ContentType rightType = rightRoot->contentType();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000100
Rui Ueyama6a607b62013-10-18 02:56:31 +0000101 if (leftType != rightType) {
102 DEBUG(reason = formatReason("contentType", (int)leftType, (int)rightType));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000103 return leftType < rightType;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000104 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000105
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000106 // Sort by .o order.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000107 const File *leftFile = &leftRoot->file();
108 const File *rightFile = &rightRoot->file();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000109
Rui Ueyama6a607b62013-10-18 02:56:31 +0000110 if (leftFile != rightFile) {
111 DEBUG(reason = formatReason(".o order", (int)leftFile->ordinal(),
112 (int)rightFile->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000113 return leftFile->ordinal() < rightFile->ordinal();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000114 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000115
116 // Sort by atom order with .o file.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000117 uint64_t leftOrdinal = leftRoot->ordinal();
118 uint64_t rightOrdinal = rightRoot->ordinal();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000119
Rui Ueyama6a607b62013-10-18 02:56:31 +0000120 if (leftOrdinal != rightOrdinal) {
Rui Ueyama46bf8282013-10-19 03:18:18 +0000121 DEBUG(reason = formatReason("ordinal", (int)leftRoot->ordinal(),
122 (int)rightRoot->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000123 return leftOrdinal < rightOrdinal;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000124 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000125
Rui Ueyamacd480752013-11-27 01:33:42 +0000126 llvm::errs() << "Unordered: <" << left->name() << "> <"
127 << right->name() << ">\n";
Shankar Easwaranbcf36562013-10-11 01:50:04 +0000128 llvm_unreachable("Atoms with Same Ordinal!");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000129}
130
Rui Ueyama5af46222013-12-08 03:24:09 +0000131static bool compareAtoms(const LayoutPass::SortKey &lc,
132 const LayoutPass::SortKey &rc) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000133 std::string reason;
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000134 bool result = compareAtomsSub(lc, rc, reason);
Rui Ueyama6a607b62013-10-18 02:56:31 +0000135 DEBUG({
Rui Ueyama4050b202013-10-18 03:18:52 +0000136 StringRef comp = result ? "<" : ">=";
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000137 llvm::dbgs() << "Layout: '" << lc._atom->name() << "' " << comp << " '"
138 << rc._atom->name() << "' (" << reason << ")\n";
Rui Ueyama6a607b62013-10-18 02:56:31 +0000139 });
140 return result;
141}
142
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000143// Returns the atom immediately followed by the given atom in the followon
144// chain.
145const DefinedAtom *LayoutPass::findAtomFollowedBy(
146 const DefinedAtom *targetAtom) {
147 // Start from the beginning of the chain and follow the chain until
148 // we find the targetChain.
149 const DefinedAtom *atom = _followOnRoots[targetAtom];
150 while (true) {
151 const DefinedAtom *prevAtom = atom;
152 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
153 // The target atom must be in the chain of its root.
154 assert(targetFollowOnAtomsIter != _followOnNexts.end());
155 atom = targetFollowOnAtomsIter->second;
156 if (atom == targetAtom)
157 return prevAtom;
158 }
159}
160
161// Check if all the atoms followed by the given target atom are of size zero.
162// When this method is called, an atom being added is not of size zero and
163// will be added to the head of the followon chain. All the atoms between the
164// atom and the targetAtom (specified by layout-after) need to be of size zero
165// in this case. Otherwise the desired layout is impossible.
166bool LayoutPass::checkAllPrevAtomsZeroSize(const DefinedAtom *targetAtom) {
167 const DefinedAtom *atom = _followOnRoots[targetAtom];
168 while (true) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000169 if (atom == targetAtom)
170 return true;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000171 if (atom->size() != 0)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000172 // TODO: print warning that an impossible layout is being desired by the
173 // user.
174 return false;
Rui Ueyama5ec6d1a2013-05-14 01:51:56 +0000175 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
176 // The target atom must be in the chain of its root.
177 assert(targetFollowOnAtomsIter != _followOnNexts.end());
178 atom = targetFollowOnAtomsIter->second;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000179 }
180}
181
182// Set the root of all atoms in targetAtom's chain to the given root.
183void LayoutPass::setChainRoot(const DefinedAtom *targetAtom,
184 const DefinedAtom *root) {
185 // Walk through the followon chain and override each node's root.
186 while (true) {
187 _followOnRoots[targetAtom] = root;
188 AtomToAtomT::iterator targetFollowOnAtomsIter =
189 _followOnNexts.find(targetAtom);
190 if (targetFollowOnAtomsIter == _followOnNexts.end())
191 return;
192 targetAtom = targetFollowOnAtomsIter->second;
193 }
194}
195
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000196/// This pass builds the followon tables described by two DenseMaps
197/// followOnRoots and followonNexts.
198/// The followOnRoots map contains a mapping of a DefinedAtom to its root
199/// The followOnNexts map contains a mapping of what DefinedAtom follows the
200/// current Atom
201/// The algorithm follows a very simple approach
202/// a) If the atom is first seen, then make that as the root atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000203/// b) The targetAtom which this Atom contains, has the root thats set to the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000204/// root of the current atom
205/// c) If the targetAtom is part of a different tree and the root of the
206/// targetAtom is itself, Chain all the atoms that are contained in the tree
207/// to the current Tree
208/// d) If the targetAtom is part of a different chain and the root of the
209/// targetAtom until the targetAtom has all atoms of size 0, then chain the
210/// targetAtoms and its tree to the current chain
211void LayoutPass::buildFollowOnTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000212 ScopedTask task(getDefaultDomain(), "LayoutPass::buildFollowOnTable");
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000213 // Set the initial size of the followon and the followonNext hash to the
214 // number of atoms that we have.
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000215 _followOnRoots.resize(range.size());
216 _followOnNexts.resize(range.size());
Rui Ueyama0196d1062013-05-14 16:53:59 +0000217 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000218 for (const Reference *r : *ai) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000219 if (r->kind() != lld::Reference::kindLayoutAfter)
220 continue;
Rui Ueyamac1800be2013-11-05 01:37:40 +0000221 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000222 _followOnNexts[ai] = targetAtom;
223
Alp Toker22593762013-12-02 01:28:14 +0000224 // If we find a followon for the first time, let's make that atom as the
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000225 // root atom.
226 if (_followOnRoots.count(ai) == 0)
227 _followOnRoots[ai] = ai;
228
229 auto iter = _followOnRoots.find(targetAtom);
230 if (iter == _followOnRoots.end()) {
Alp Toker22593762013-12-02 01:28:14 +0000231 // If the targetAtom is not a root of any chain, let's make the root of
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000232 // the targetAtom to the root of the current chain.
233 _followOnRoots[targetAtom] = _followOnRoots[ai];
234 } else if (iter->second == targetAtom) {
235 // If the targetAtom is the root of a chain, the chain becomes part of
236 // the current chain. Rewrite the subchain's root to the current
237 // chain's root.
238 setChainRoot(targetAtom, _followOnRoots[ai]);
239 } else {
240 // The targetAtom is already a part of a chain. If the current atom is
241 // of size zero, we can insert it in the middle of the chain just
242 // before the target atom, while not breaking other atom's followon
243 // relationships. If it's not, we can only insert the current atom at
244 // the beginning of the chain. All the atoms followed by the target
245 // atom must be of size zero in that case to satisfy the followon
246 // relationships.
Rui Ueyama0196d1062013-05-14 16:53:59 +0000247 size_t currentAtomSize = ai->size();
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000248 if (currentAtomSize == 0) {
249 const DefinedAtom *targetPrevAtom = findAtomFollowedBy(targetAtom);
250 _followOnNexts[targetPrevAtom] = ai;
251 _followOnRoots[ai] = _followOnRoots[targetPrevAtom];
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000252 } else {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000253 if (!checkAllPrevAtomsZeroSize(targetAtom))
254 break;
255 _followOnNexts[ai] = _followOnRoots[targetAtom];
256 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
257 }
258 }
259 }
260 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000261}
262
263/// This pass builds the followon tables using InGroup relationships
264/// The algorithm follows a very simple approach
265/// a) If the rootAtom is not part of any root, create a new root with the
266/// as the head
267/// b) If the current Atom root is not found, then make the current atoms root
268/// point to the rootAtom
269/// c) If the root of the current Atom is itself a root of some other tree
270/// make all the atoms in the chain point to the ingroup reference
271/// d) Check to see if the current atom is part of the chain from the rootAtom
272/// if not add the atom to the chain, so that the current atom is part of the
273/// the chain where the rootAtom is in
274void LayoutPass::buildInGroupTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000275 ScopedTask task(getDefaultDomain(), "LayoutPass::buildInGroupTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000276 // This table would convert precededby references to follow on
277 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000278 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000279 for (const Reference *r : *ai) {
280 if (r->kind() == lld::Reference::kindInGroup) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000281 const DefinedAtom *rootAtom = dyn_cast<DefinedAtom>(r->target());
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000282 // If the root atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000283 // create a new root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000284 if (_followOnRoots.count(rootAtom) == 0) {
285 _followOnRoots[rootAtom] = rootAtom;
286 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000287 // If the current Atom has not been seen yet and there is no root
288 // that has been set, set the root of the atom to the targetAtom
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000289 // as the targetAtom points to the ingroup root
290 auto iter = _followOnRoots.find(ai);
291 if (iter == _followOnRoots.end()) {
292 _followOnRoots[ai] = rootAtom;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000293 } else if (iter->second == ai) {
294 if (iter->second != rootAtom)
295 setChainRoot(iter->second, rootAtom);
296 } else {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000297 // TODO : Flag an error that the root of the tree
298 // is different, Here is an example
299 // Say there are atoms
300 // chain 1 : a->b->c
301 // chain 2 : d->e->f
302 // and e,f have their ingroup reference as a
303 // this could happen only if the root of e,f that is d
304 // has root as 'a'
305 continue;
306 }
307
308 // Check if the current atom is part of the chain
309 bool isAtomInChain = false;
310 const DefinedAtom *lastAtom = rootAtom;
311 while (true) {
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000312 AtomToAtomT::iterator followOnAtomsIter =
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000313 _followOnNexts.find(lastAtom);
314 if (followOnAtomsIter != _followOnNexts.end()) {
315 lastAtom = followOnAtomsIter->second;
316 if (lastAtom == ai) {
317 isAtomInChain = true;
318 break;
319 }
320 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000321 else
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000322 break;
323 } // findAtomInChain
324
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000325 if (!isAtomInChain)
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000326 _followOnNexts[lastAtom] = ai;
327 }
328 }
329 }
330}
331
332/// This pass builds the followon tables using Preceded By relationships
333/// The algorithm follows a very simple approach
334/// a) If the targetAtom is not part of any root and the current atom is not
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000335/// part of any root, create a chain with the current atom as root and
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000336/// the targetAtom as following the current atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000337/// b) Chain the targetAtom to the current Atom if the targetAtom is not part
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000338/// of any chain and the currentAtom has no followOn's
339/// c) If the targetAtom is part of a different tree and the root of the
340/// targetAtom is itself, and if the current atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000341/// chain all the atoms together
342/// d) If the current atom has no followon and the root of the targetAtom is
343/// not equal to the root of the current atom(the targetAtom is not in the
344/// same chain), chain all the atoms that are lead by the targetAtom into
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000345/// the current chain
346void LayoutPass::buildPrecededByTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000347 ScopedTask task(getDefaultDomain(), "LayoutPass::buildPrecededByTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000348 // This table would convert precededby references to follow on
349 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000350 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000351 for (const Reference *r : *ai) {
352 if (r->kind() == lld::Reference::kindLayoutBefore) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000353 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000354 // Is the targetAtom not chained
355 if (_followOnRoots.count(targetAtom) == 0) {
356 // Is the current atom not part of any root ?
357 if (_followOnRoots.count(ai) == 0) {
358 _followOnRoots[ai] = ai;
359 _followOnNexts[ai] = targetAtom;
360 _followOnRoots[targetAtom] = _followOnRoots[ai];
361 } else if (_followOnNexts.count(ai) == 0) {
362 // Chain the targetAtom to the current Atom
363 // if the currentAtom has no followon references
364 _followOnNexts[ai] = targetAtom;
365 _followOnRoots[targetAtom] = _followOnRoots[ai];
366 }
367 } else if (_followOnRoots.find(targetAtom)->second == targetAtom) {
368 // Is the targetAtom in chain with the targetAtom as the root ?
369 bool changeRoots = false;
370 if (_followOnRoots.count(ai) == 0) {
371 _followOnRoots[ai] = ai;
372 _followOnNexts[ai] = targetAtom;
373 _followOnRoots[targetAtom] = _followOnRoots[ai];
374 changeRoots = true;
375 } else if (_followOnNexts.count(ai) == 0) {
376 // Chain the targetAtom to the current Atom
377 // if the currentAtom has no followon references
378 if (_followOnRoots[ai] != _followOnRoots[targetAtom]) {
379 _followOnNexts[ai] = targetAtom;
380 _followOnRoots[targetAtom] = _followOnRoots[ai];
381 changeRoots = true;
382 }
383 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000384 // Change the roots of the targetAtom and its chain to
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000385 // the current atoms root
386 if (changeRoots) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000387 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
388 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000389 } // Is targetAtom root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000390 } // kindLayoutBefore
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000391 } // Reference
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000392 } // atom iteration
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000393} // end function
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000394
395
396/// Build an ordinal override map by traversing the followon chain, and
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000397/// assigning ordinals to each atom, if the atoms have their ordinals
398/// already assigned skip the atom and move to the next. This is the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000399/// main map thats used to sort the atoms while comparing two atoms together
400void LayoutPass::buildOrdinalOverrideMap(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000401 ScopedTask task(getDefaultDomain(), "LayoutPass::buildOrdinalOverrideMap");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000402 uint64_t index = 0;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000403 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000404 const DefinedAtom *atom = ai;
Michael J. Spencer1ecf8902013-03-12 00:10:00 +0000405 if (_ordinalOverrideMap.find(atom) != _ordinalOverrideMap.end())
406 continue;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000407 AtomToAtomT::iterator start = _followOnRoots.find(atom);
408 if (start != _followOnRoots.end()) {
409 for (const DefinedAtom *nextAtom = start->second; nextAtom != NULL;
410 nextAtom = _followOnNexts[nextAtom]) {
411 AtomToOrdinalT::iterator pos = _ordinalOverrideMap.find(nextAtom);
412 if (pos == _ordinalOverrideMap.end()) {
413 _ordinalOverrideMap[nextAtom] = index++;
414 }
415 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000416 }
417 }
418}
419
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000420// Helper functions to check follow-on graph.
421#ifndef NDEBUG
422namespace {
423typedef llvm::DenseMap<const DefinedAtom *, const DefinedAtom *> AtomToAtomT;
424
425std::string atomToDebugString(const Atom *atom) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000426 const DefinedAtom *definedAtom = dyn_cast<DefinedAtom>(atom);
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000427 std::string str;
428 llvm::raw_string_ostream s(str);
429 if (definedAtom->name().empty())
430 s << "<anonymous " << definedAtom << ">";
431 else
432 s << definedAtom->name();
433 s << " in ";
434 if (definedAtom->customSectionName().empty())
435 s << "<anonymous>";
436 else
437 s << definedAtom->customSectionName();
438 s.flush();
439 return str;
440}
441
442void showCycleDetectedError(AtomToAtomT &followOnNexts,
443 const DefinedAtom *atom) {
444 const DefinedAtom *start = atom;
445 llvm::dbgs() << "There's a cycle in a follow-on chain!\n";
446 do {
447 llvm::dbgs() << " " << atomToDebugString(atom) << "\n";
448 for (const Reference *ref : *atom) {
449 llvm::dbgs() << " " << ref->kindToString()
450 << ": " << atomToDebugString(ref->target()) << "\n";
451 }
452 atom = followOnNexts[atom];
453 } while (atom != start);
Rui Ueyama5b274f32013-07-29 21:50:33 +0000454 llvm::report_fatal_error("Cycle detected");
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000455}
456
457/// Exit if there's a cycle in a followon chain reachable from the
458/// given root atom. Uses the tortoise and hare algorithm to detect a
459/// cycle.
460void checkNoCycleInFollowonChain(AtomToAtomT &followOnNexts,
461 const DefinedAtom *root) {
462 const DefinedAtom *tortoise = root;
463 const DefinedAtom *hare = followOnNexts[root];
464 while (true) {
465 if (!tortoise || !hare)
466 return;
467 if (tortoise == hare)
468 showCycleDetectedError(followOnNexts, tortoise);
469 tortoise = followOnNexts[tortoise];
470 hare = followOnNexts[followOnNexts[hare]];
471 }
472}
473
474void checkReachabilityFromRoot(AtomToAtomT &followOnRoots,
475 const DefinedAtom *atom) {
476 if (!atom) return;
477 auto i = followOnRoots.find(atom);
478 if (i == followOnRoots.end()) {
479 Twine msg(Twine("Atom <") + atomToDebugString(atom)
480 + "> has no follow-on root!");
481 llvm_unreachable(msg.str().c_str());
482 }
483 const DefinedAtom *ap = i->second;
484 while (true) {
485 const DefinedAtom *next = followOnRoots[ap];
486 if (!next) {
487 Twine msg(Twine("Atom <" + atomToDebugString(atom)
488 + "> is not reachable from its root!"));
489 llvm_unreachable(msg.str().c_str());
490 }
491 if (next == ap)
492 return;
493 ap = next;
494 }
495}
496
497void printDefinedAtoms(const MutableFile::DefinedAtomRange &atomRange) {
498 for (const DefinedAtom *atom : atomRange) {
499 llvm::dbgs() << " file=" << atom->file().path()
500 << ", name=" << atom->name()
501 << ", size=" << atom->size()
502 << ", type=" << atom->contentType()
503 << ", ordinal=" << atom->ordinal()
504 << "\n";
505 }
506}
507} // end anonymous namespace
508
509/// Verify that the followon chain is sane. Should not be called in
510/// release binary.
511void LayoutPass::checkFollowonChain(MutableFile::DefinedAtomRange &range) {
512 ScopedTask task(getDefaultDomain(), "LayoutPass::checkFollowonChain");
513
514 // Verify that there's no cycle in follow-on chain.
515 std::set<const DefinedAtom *> roots;
516 for (const auto &ai : _followOnRoots)
517 roots.insert(ai.second);
518 for (const DefinedAtom *root : roots)
519 checkNoCycleInFollowonChain(_followOnNexts, root);
520
521 // Verify that all the atoms in followOnNexts have references to
522 // their roots.
523 for (const auto &ai : _followOnNexts) {
524 checkReachabilityFromRoot(_followOnRoots, ai.first);
525 checkReachabilityFromRoot(_followOnRoots, ai.second);
526 }
527}
528#endif // #ifndef NDEBUG
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}