blob: 77a484eaf0a22402bb92ad7d4e06040b3730c997 [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 Ueyamaa6b71ca2013-06-07 20:18:39 +000012#include <set>
13
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000014#include "lld/Passes/LayoutPass.h"
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +000015#include "lld/Core/Instrumentation.h"
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +000016
17#include "llvm/ADT/Twine.h"
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000018#include "llvm/Support/Debug.h"
19
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000020using namespace lld;
21
Rui Ueyama52062222013-10-18 03:18:54 +000022#ifndef NDEBUG
Rui Ueyama6a607b62013-10-18 02:56:31 +000023namespace {
24// Return "reason (leftval, rightval)"
25std::string formatReason(StringRef reason, int leftVal, int rightVal) {
26 Twine msg =
27 Twine(reason) + " (" + Twine(leftVal) + ", " + Twine(rightVal) + ")";
28 return std::move(msg.str());
29}
Rui Ueyama46bf8282013-10-19 03:18:18 +000030} // end anonymous namespace
31
32// Less-than relationship of two atoms must be transitive, which is, if a < b
33// and b < c, a < c must be true. This function checks the transitivity by
34// checking the sort results.
35void LayoutPass::checkTransitivity(DefinedAtomIter begin,
36 DefinedAtomIter end) const {
37 for (DefinedAtomIter i = begin; (i + 1) != end; ++i) {
38 for (DefinedAtomIter j = i + 1; j != end; ++j) {
39 assert(_compareAtoms(*i, *j));
40 assert(!_compareAtoms(*j, *i));
41 }
42 }
Rui Ueyama6a607b62013-10-18 02:56:31 +000043}
Rui Ueyama52062222013-10-18 03:18:54 +000044#endif // NDEBUG
Rui Ueyama6a607b62013-10-18 02:56:31 +000045
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000046/// The function compares atoms by sorting atoms in the following order
Shankar Easwarand6d1b522013-09-12 15:59:34 +000047/// a) Sorts atoms by Section position preference
48/// b) Sorts atoms by their ordinal overrides
49/// (layout-after/layout-before/ingroup)
50/// c) Sorts atoms by their permissions
51/// d) Sorts atoms by their content
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000052/// e) Sorts atoms on how they appear using File Ordinality
53/// f) Sorts atoms on how they appear within the File
Rui Ueyama6a607b62013-10-18 02:56:31 +000054bool LayoutPass::CompareAtoms::compare(const DefinedAtom *left,
55 const DefinedAtom *right,
56 std::string &reason) const {
57 if (left == right) {
58 reason = "same";
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000059 return false;
Rui Ueyama6a607b62013-10-18 02:56:31 +000060 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000061
Shankar Easwarand8da9892013-05-22 17:41:04 +000062 // Sort by section position preference.
63 DefinedAtom::SectionPosition leftPos = left->sectionPosition();
64 DefinedAtom::SectionPosition rightPos = right->sectionPosition();
65
Shankar Easwarand8da9892013-05-22 17:41:04 +000066 bool leftSpecialPos = (leftPos != DefinedAtom::sectionPositionAny);
67 bool rightSpecialPos = (rightPos != DefinedAtom::sectionPositionAny);
68 if (leftSpecialPos || rightSpecialPos) {
Rui Ueyama6a607b62013-10-18 02:56:31 +000069 if (leftPos != rightPos) {
70 DEBUG(reason = formatReason("sectionPos", (int)leftPos, (int)rightPos));
Shankar Easwarand8da9892013-05-22 17:41:04 +000071 return leftPos < rightPos;
Rui Ueyama6a607b62013-10-18 02:56:31 +000072 }
Shankar Easwarand8da9892013-05-22 17:41:04 +000073 }
74
Rui Ueyama46bf8282013-10-19 03:18:18 +000075 // Find the root of the chain if it is a part of a follow-on chain.
76 auto leftFind = _layout._followOnRoots.find(left);
77 auto rightFind = _layout._followOnRoots.find(right);
78 const DefinedAtom *leftRoot =
79 (leftFind == _layout._followOnRoots.end()) ? left : leftFind->second;
80 const DefinedAtom *rightRoot =
81 (rightFind == _layout._followOnRoots.end()) ? right : rightFind->second;
Shankar Easwaranf1b341c2013-09-12 15:43:09 +000082
83 // Sort atoms by their ordinal overrides only if they fall in the same
84 // chain.
Rui Ueyama46bf8282013-10-19 03:18:18 +000085 AtomToOrdinalT::const_iterator lPos = _layout._ordinalOverrideMap.find(left);
86 AtomToOrdinalT::const_iterator rPos = _layout._ordinalOverrideMap.find(right);
87 AtomToOrdinalT::const_iterator end = _layout._ordinalOverrideMap.end();
88 if (leftRoot == rightRoot && lPos != end && rPos != end) {
89 DEBUG(reason = formatReason("override", lPos->second, rPos->second));
90 return lPos->second < rPos->second;
Shankar Easwaran3c5d2c82013-05-10 16:44:02 +000091 }
92
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000093 // Sort same permissions together.
Rui Ueyama46bf8282013-10-19 03:18:18 +000094 DefinedAtom::ContentPermissions leftPerms = leftRoot->permissions();
95 DefinedAtom::ContentPermissions rightPerms = rightRoot->permissions();
Shankar Easwaran8c256852013-03-13 04:05:38 +000096
Rui Ueyama6a607b62013-10-18 02:56:31 +000097 if (leftPerms != rightPerms) {
98 DEBUG(reason =
99 formatReason("contentPerms", (int)leftPerms, (int)rightPerms));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000100 return leftPerms < rightPerms;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000101 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000102
103 // Sort same content types together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000104 DefinedAtom::ContentType leftType = leftRoot->contentType();
105 DefinedAtom::ContentType rightType = rightRoot->contentType();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000106
Rui Ueyama6a607b62013-10-18 02:56:31 +0000107 if (leftType != rightType) {
108 DEBUG(reason = formatReason("contentType", (int)leftType, (int)rightType));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000109 return leftType < rightType;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000110 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000111
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000112 // Sort by .o order.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000113 const File *leftFile = &leftRoot->file();
114 const File *rightFile = &rightRoot->file();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000115
Rui Ueyama6a607b62013-10-18 02:56:31 +0000116 if (leftFile != rightFile) {
117 DEBUG(reason = formatReason(".o order", (int)leftFile->ordinal(),
118 (int)rightFile->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000119 return leftFile->ordinal() < rightFile->ordinal();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000120 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000121
122 // Sort by atom order with .o file.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000123 uint64_t leftOrdinal = leftRoot->ordinal();
124 uint64_t rightOrdinal = rightRoot->ordinal();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000125
Rui Ueyama6a607b62013-10-18 02:56:31 +0000126 if (leftOrdinal != rightOrdinal) {
Rui Ueyama46bf8282013-10-19 03:18:18 +0000127 DEBUG(reason = formatReason("ordinal", (int)leftRoot->ordinal(),
128 (int)rightRoot->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000129 return leftOrdinal < rightOrdinal;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000130 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000131
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +0000132 DEBUG(llvm::dbgs() << "Unordered\n");
Shankar Easwaranbcf36562013-10-11 01:50:04 +0000133 llvm_unreachable("Atoms with Same Ordinal!");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000134}
135
Rui Ueyama6a607b62013-10-18 02:56:31 +0000136bool LayoutPass::CompareAtoms::operator()(const DefinedAtom *left,
137 const DefinedAtom *right) const {
138 std::string reason;
139 bool result = compare(left, right, reason);
140 DEBUG({
Rui Ueyama4050b202013-10-18 03:18:52 +0000141 StringRef comp = result ? "<" : ">=";
Rui Ueyama6a607b62013-10-18 02:56:31 +0000142 llvm::dbgs() << "Layout: '" << left->name() << "' " << comp << " '"
143 << right->name() << "' (" << reason << ")\n";
144 });
145 return result;
146}
147
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000148// Returns the atom immediately followed by the given atom in the followon
149// chain.
150const DefinedAtom *LayoutPass::findAtomFollowedBy(
151 const DefinedAtom *targetAtom) {
152 // Start from the beginning of the chain and follow the chain until
153 // we find the targetChain.
154 const DefinedAtom *atom = _followOnRoots[targetAtom];
155 while (true) {
156 const DefinedAtom *prevAtom = atom;
157 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
158 // The target atom must be in the chain of its root.
159 assert(targetFollowOnAtomsIter != _followOnNexts.end());
160 atom = targetFollowOnAtomsIter->second;
161 if (atom == targetAtom)
162 return prevAtom;
163 }
164}
165
166// Check if all the atoms followed by the given target atom are of size zero.
167// When this method is called, an atom being added is not of size zero and
168// will be added to the head of the followon chain. All the atoms between the
169// atom and the targetAtom (specified by layout-after) need to be of size zero
170// in this case. Otherwise the desired layout is impossible.
171bool LayoutPass::checkAllPrevAtomsZeroSize(const DefinedAtom *targetAtom) {
172 const DefinedAtom *atom = _followOnRoots[targetAtom];
173 while (true) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000174 if (atom == targetAtom)
175 return true;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000176 if (atom->size() != 0)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000177 // TODO: print warning that an impossible layout is being desired by the
178 // user.
179 return false;
Rui Ueyama5ec6d1a2013-05-14 01:51:56 +0000180 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
181 // The target atom must be in the chain of its root.
182 assert(targetFollowOnAtomsIter != _followOnNexts.end());
183 atom = targetFollowOnAtomsIter->second;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000184 }
185}
186
187// Set the root of all atoms in targetAtom's chain to the given root.
188void LayoutPass::setChainRoot(const DefinedAtom *targetAtom,
189 const DefinedAtom *root) {
190 // Walk through the followon chain and override each node's root.
191 while (true) {
192 _followOnRoots[targetAtom] = root;
193 AtomToAtomT::iterator targetFollowOnAtomsIter =
194 _followOnNexts.find(targetAtom);
195 if (targetFollowOnAtomsIter == _followOnNexts.end())
196 return;
197 targetAtom = targetFollowOnAtomsIter->second;
198 }
199}
200
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000201/// This pass builds the followon tables described by two DenseMaps
202/// followOnRoots and followonNexts.
203/// The followOnRoots map contains a mapping of a DefinedAtom to its root
204/// The followOnNexts map contains a mapping of what DefinedAtom follows the
205/// current Atom
206/// The algorithm follows a very simple approach
207/// a) If the atom is first seen, then make that as the root atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000208/// b) The targetAtom which this Atom contains, has the root thats set to the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000209/// root of the current atom
210/// c) If the targetAtom is part of a different tree and the root of the
211/// targetAtom is itself, Chain all the atoms that are contained in the tree
212/// to the current Tree
213/// d) If the targetAtom is part of a different chain and the root of the
214/// targetAtom until the targetAtom has all atoms of size 0, then chain the
215/// targetAtoms and its tree to the current chain
216void LayoutPass::buildFollowOnTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000217 ScopedTask task(getDefaultDomain(), "LayoutPass::buildFollowOnTable");
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000218 // Set the initial size of the followon and the followonNext hash to the
219 // number of atoms that we have.
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000220 _followOnRoots.resize(range.size());
221 _followOnNexts.resize(range.size());
Rui Ueyama0196d1062013-05-14 16:53:59 +0000222 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000223 for (const Reference *r : *ai) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000224 if (r->kind() != lld::Reference::kindLayoutAfter)
225 continue;
226 const DefinedAtom *targetAtom = llvm::dyn_cast<DefinedAtom>(r->target());
227 _followOnNexts[ai] = targetAtom;
228
229 // If we find a followon for the first time, lets make that atom as the
230 // root atom.
231 if (_followOnRoots.count(ai) == 0)
232 _followOnRoots[ai] = ai;
233
234 auto iter = _followOnRoots.find(targetAtom);
235 if (iter == _followOnRoots.end()) {
236 // If the targetAtom is not a root of any chain, lets make the root of
237 // the targetAtom to the root of the current chain.
238 _followOnRoots[targetAtom] = _followOnRoots[ai];
239 } else if (iter->second == targetAtom) {
240 // If the targetAtom is the root of a chain, the chain becomes part of
241 // the current chain. Rewrite the subchain's root to the current
242 // chain's root.
243 setChainRoot(targetAtom, _followOnRoots[ai]);
244 } else {
245 // The targetAtom is already a part of a chain. If the current atom is
246 // of size zero, we can insert it in the middle of the chain just
247 // before the target atom, while not breaking other atom's followon
248 // relationships. If it's not, we can only insert the current atom at
249 // the beginning of the chain. All the atoms followed by the target
250 // atom must be of size zero in that case to satisfy the followon
251 // relationships.
Rui Ueyama0196d1062013-05-14 16:53:59 +0000252 size_t currentAtomSize = ai->size();
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000253 if (currentAtomSize == 0) {
254 const DefinedAtom *targetPrevAtom = findAtomFollowedBy(targetAtom);
255 _followOnNexts[targetPrevAtom] = ai;
256 _followOnRoots[ai] = _followOnRoots[targetPrevAtom];
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000257 } else {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000258 if (!checkAllPrevAtomsZeroSize(targetAtom))
259 break;
260 _followOnNexts[ai] = _followOnRoots[targetAtom];
261 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
262 }
263 }
264 }
265 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000266}
267
268/// This pass builds the followon tables using InGroup relationships
269/// The algorithm follows a very simple approach
270/// a) If the rootAtom is not part of any root, create a new root with the
271/// as the head
272/// b) If the current Atom root is not found, then make the current atoms root
273/// point to the rootAtom
274/// c) If the root of the current Atom is itself a root of some other tree
275/// make all the atoms in the chain point to the ingroup reference
276/// d) Check to see if the current atom is part of the chain from the rootAtom
277/// if not add the atom to the chain, so that the current atom is part of the
278/// the chain where the rootAtom is in
279void LayoutPass::buildInGroupTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000280 ScopedTask task(getDefaultDomain(), "LayoutPass::buildInGroupTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000281 // This table would convert precededby references to follow on
282 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000283 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000284 for (const Reference *r : *ai) {
285 if (r->kind() == lld::Reference::kindInGroup) {
286 const DefinedAtom *rootAtom = llvm::dyn_cast<DefinedAtom>(r->target());
287 // If the root atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000288 // create a new root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000289 if (_followOnRoots.count(rootAtom) == 0) {
290 _followOnRoots[rootAtom] = rootAtom;
291 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000292 // If the current Atom has not been seen yet and there is no root
293 // that has been set, set the root of the atom to the targetAtom
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000294 // as the targetAtom points to the ingroup root
295 auto iter = _followOnRoots.find(ai);
296 if (iter == _followOnRoots.end()) {
297 _followOnRoots[ai] = rootAtom;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000298 } else if (iter->second == ai) {
299 if (iter->second != rootAtom)
300 setChainRoot(iter->second, rootAtom);
301 } else {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000302 // TODO : Flag an error that the root of the tree
303 // is different, Here is an example
304 // Say there are atoms
305 // chain 1 : a->b->c
306 // chain 2 : d->e->f
307 // and e,f have their ingroup reference as a
308 // this could happen only if the root of e,f that is d
309 // has root as 'a'
310 continue;
311 }
312
313 // Check if the current atom is part of the chain
314 bool isAtomInChain = false;
315 const DefinedAtom *lastAtom = rootAtom;
316 while (true) {
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000317 AtomToAtomT::iterator followOnAtomsIter =
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000318 _followOnNexts.find(lastAtom);
319 if (followOnAtomsIter != _followOnNexts.end()) {
320 lastAtom = followOnAtomsIter->second;
321 if (lastAtom == ai) {
322 isAtomInChain = true;
323 break;
324 }
325 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000326 else
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000327 break;
328 } // findAtomInChain
329
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000330 if (!isAtomInChain)
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000331 _followOnNexts[lastAtom] = ai;
332 }
333 }
334 }
335}
336
337/// This pass builds the followon tables using Preceded By relationships
338/// The algorithm follows a very simple approach
339/// a) If the targetAtom is not part of any root and the current atom is not
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000340/// part of any root, create a chain with the current atom as root and
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000341/// the targetAtom as following the current atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000342/// b) Chain the targetAtom to the current Atom if the targetAtom is not part
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000343/// of any chain and the currentAtom has no followOn's
344/// c) If the targetAtom is part of a different tree and the root of the
345/// targetAtom is itself, and if the current atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000346/// chain all the atoms together
347/// d) If the current atom has no followon and the root of the targetAtom is
348/// not equal to the root of the current atom(the targetAtom is not in the
349/// same chain), chain all the atoms that are lead by the targetAtom into
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000350/// the current chain
351void LayoutPass::buildPrecededByTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000352 ScopedTask task(getDefaultDomain(), "LayoutPass::buildPrecededByTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000353 // This table would convert precededby references to follow on
354 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000355 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000356 for (const Reference *r : *ai) {
357 if (r->kind() == lld::Reference::kindLayoutBefore) {
358 const DefinedAtom *targetAtom = llvm::dyn_cast<DefinedAtom>(r->target());
359 // Is the targetAtom not chained
360 if (_followOnRoots.count(targetAtom) == 0) {
361 // Is the current atom not part of any root ?
362 if (_followOnRoots.count(ai) == 0) {
363 _followOnRoots[ai] = ai;
364 _followOnNexts[ai] = targetAtom;
365 _followOnRoots[targetAtom] = _followOnRoots[ai];
366 } else if (_followOnNexts.count(ai) == 0) {
367 // Chain the targetAtom to the current Atom
368 // if the currentAtom has no followon references
369 _followOnNexts[ai] = targetAtom;
370 _followOnRoots[targetAtom] = _followOnRoots[ai];
371 }
372 } else if (_followOnRoots.find(targetAtom)->second == targetAtom) {
373 // Is the targetAtom in chain with the targetAtom as the root ?
374 bool changeRoots = false;
375 if (_followOnRoots.count(ai) == 0) {
376 _followOnRoots[ai] = ai;
377 _followOnNexts[ai] = targetAtom;
378 _followOnRoots[targetAtom] = _followOnRoots[ai];
379 changeRoots = true;
380 } else if (_followOnNexts.count(ai) == 0) {
381 // Chain the targetAtom to the current Atom
382 // if the currentAtom has no followon references
383 if (_followOnRoots[ai] != _followOnRoots[targetAtom]) {
384 _followOnNexts[ai] = targetAtom;
385 _followOnRoots[targetAtom] = _followOnRoots[ai];
386 changeRoots = true;
387 }
388 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000389 // Change the roots of the targetAtom and its chain to
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000390 // the current atoms root
391 if (changeRoots) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000392 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
393 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000394 } // Is targetAtom root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000395 } // kindLayoutBefore
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000396 } // Reference
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000397 } // atom iteration
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000398} // end function
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000399
400
401/// Build an ordinal override map by traversing the followon chain, and
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000402/// assigning ordinals to each atom, if the atoms have their ordinals
403/// already assigned skip the atom and move to the next. This is the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000404/// main map thats used to sort the atoms while comparing two atoms together
405void LayoutPass::buildOrdinalOverrideMap(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000406 ScopedTask task(getDefaultDomain(), "LayoutPass::buildOrdinalOverrideMap");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000407 uint64_t index = 0;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000408 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000409 const DefinedAtom *atom = ai;
Michael J. Spencer1ecf8902013-03-12 00:10:00 +0000410 if (_ordinalOverrideMap.find(atom) != _ordinalOverrideMap.end())
411 continue;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000412 AtomToAtomT::iterator start = _followOnRoots.find(atom);
413 if (start != _followOnRoots.end()) {
414 for (const DefinedAtom *nextAtom = start->second; nextAtom != NULL;
415 nextAtom = _followOnNexts[nextAtom]) {
416 AtomToOrdinalT::iterator pos = _ordinalOverrideMap.find(nextAtom);
417 if (pos == _ordinalOverrideMap.end()) {
418 _ordinalOverrideMap[nextAtom] = index++;
419 }
420 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000421 }
422 }
423}
424
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000425// Helper functions to check follow-on graph.
426#ifndef NDEBUG
427namespace {
428typedef llvm::DenseMap<const DefinedAtom *, const DefinedAtom *> AtomToAtomT;
429
430std::string atomToDebugString(const Atom *atom) {
431 const DefinedAtom *definedAtom = llvm::dyn_cast<DefinedAtom>(atom);
432 std::string str;
433 llvm::raw_string_ostream s(str);
434 if (definedAtom->name().empty())
435 s << "<anonymous " << definedAtom << ">";
436 else
437 s << definedAtom->name();
438 s << " in ";
439 if (definedAtom->customSectionName().empty())
440 s << "<anonymous>";
441 else
442 s << definedAtom->customSectionName();
443 s.flush();
444 return str;
445}
446
447void showCycleDetectedError(AtomToAtomT &followOnNexts,
448 const DefinedAtom *atom) {
449 const DefinedAtom *start = atom;
450 llvm::dbgs() << "There's a cycle in a follow-on chain!\n";
451 do {
452 llvm::dbgs() << " " << atomToDebugString(atom) << "\n";
453 for (const Reference *ref : *atom) {
454 llvm::dbgs() << " " << ref->kindToString()
455 << ": " << atomToDebugString(ref->target()) << "\n";
456 }
457 atom = followOnNexts[atom];
458 } while (atom != start);
Rui Ueyama5b274f32013-07-29 21:50:33 +0000459 llvm::report_fatal_error("Cycle detected");
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000460}
461
462/// Exit if there's a cycle in a followon chain reachable from the
463/// given root atom. Uses the tortoise and hare algorithm to detect a
464/// cycle.
465void checkNoCycleInFollowonChain(AtomToAtomT &followOnNexts,
466 const DefinedAtom *root) {
467 const DefinedAtom *tortoise = root;
468 const DefinedAtom *hare = followOnNexts[root];
469 while (true) {
470 if (!tortoise || !hare)
471 return;
472 if (tortoise == hare)
473 showCycleDetectedError(followOnNexts, tortoise);
474 tortoise = followOnNexts[tortoise];
475 hare = followOnNexts[followOnNexts[hare]];
476 }
477}
478
479void checkReachabilityFromRoot(AtomToAtomT &followOnRoots,
480 const DefinedAtom *atom) {
481 if (!atom) return;
482 auto i = followOnRoots.find(atom);
483 if (i == followOnRoots.end()) {
484 Twine msg(Twine("Atom <") + atomToDebugString(atom)
485 + "> has no follow-on root!");
486 llvm_unreachable(msg.str().c_str());
487 }
488 const DefinedAtom *ap = i->second;
489 while (true) {
490 const DefinedAtom *next = followOnRoots[ap];
491 if (!next) {
492 Twine msg(Twine("Atom <" + atomToDebugString(atom)
493 + "> is not reachable from its root!"));
494 llvm_unreachable(msg.str().c_str());
495 }
496 if (next == ap)
497 return;
498 ap = next;
499 }
500}
501
502void printDefinedAtoms(const MutableFile::DefinedAtomRange &atomRange) {
503 for (const DefinedAtom *atom : atomRange) {
504 llvm::dbgs() << " file=" << atom->file().path()
505 << ", name=" << atom->name()
506 << ", size=" << atom->size()
507 << ", type=" << atom->contentType()
508 << ", ordinal=" << atom->ordinal()
509 << "\n";
510 }
511}
512} // end anonymous namespace
513
514/// Verify that the followon chain is sane. Should not be called in
515/// release binary.
516void LayoutPass::checkFollowonChain(MutableFile::DefinedAtomRange &range) {
517 ScopedTask task(getDefaultDomain(), "LayoutPass::checkFollowonChain");
518
519 // Verify that there's no cycle in follow-on chain.
520 std::set<const DefinedAtom *> roots;
521 for (const auto &ai : _followOnRoots)
522 roots.insert(ai.second);
523 for (const DefinedAtom *root : roots)
524 checkNoCycleInFollowonChain(_followOnNexts, root);
525
526 // Verify that all the atoms in followOnNexts have references to
527 // their roots.
528 for (const auto &ai : _followOnNexts) {
529 checkReachabilityFromRoot(_followOnRoots, ai.first);
530 checkReachabilityFromRoot(_followOnRoots, ai.second);
531 }
532}
533#endif // #ifndef NDEBUG
534
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000535/// Perform the actual pass
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000536void LayoutPass::perform(std::unique_ptr<MutableFile> &mergedFile) {
Michael J. Spencerbd66d042013-05-28 18:55:39 +0000537 ScopedTask task(getDefaultDomain(), "LayoutPass");
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000538 MutableFile::DefinedAtomRange atomRange = mergedFile->definedAtoms();
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000539
540 // Build follow on tables
541 buildFollowOnTable(atomRange);
542
543 // Build Ingroup reference table
544 buildInGroupTable(atomRange);
545
546 // Build preceded by tables
547 buildPrecededByTable(atomRange);
548
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000549 // Check the structure of followon graph if running in debug mode.
550 DEBUG(checkFollowonChain(atomRange));
551
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000552 // Build override maps
553 buildOrdinalOverrideMap(atomRange);
554
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000555 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000556 llvm::dbgs() << "unsorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000557 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000558 });
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000559
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000560 // sort the atoms
Shankar Easwaranbcf36562013-10-11 01:50:04 +0000561 std::sort(atomRange.begin(), atomRange.end(), _compareAtoms);
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000562
Rui Ueyama46bf8282013-10-19 03:18:18 +0000563 DEBUG(checkTransitivity(atomRange.begin(), atomRange.end()));
564
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000565 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000566 llvm::dbgs() << "sorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000567 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000568 });
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000569}