blob: bb626baabd129e7640caf72b4f0b4c0591d8ae3b [file] [log] [blame]
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001//===-- ValueEnumerator.cpp - Number values and types for bitcode writer --===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ValueEnumerator class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ValueEnumerator.h"
Rafael Espindola337a1b22011-04-06 16:49:37 +000015#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000018#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Module.h"
Duncan P. N. Exon Smith15eb0ab2014-07-25 16:13:16 +000022#include "llvm/IR/UseListOrder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/ValueSymbolTable.h"
Chad Rosier78037a92011-12-07 20:44:46 +000024#include "llvm/Support/Debug.h"
25#include "llvm/Support/raw_ostream.h"
Chris Lattnera8713be2007-05-04 05:05:48 +000026#include <algorithm>
Chris Lattnerc1d10d62007-04-22 06:24:45 +000027using namespace llvm;
28
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +000029namespace {
Duncan P. N. Exon Smith2e6a87b2014-07-29 23:03:40 +000030struct OrderMap {
31 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +000032 unsigned LastGlobalConstantID;
33 unsigned LastGlobalValueID;
34
35 OrderMap() : LastGlobalConstantID(0), LastGlobalValueID(0) {}
36
37 bool isGlobalConstant(unsigned ID) const {
38 return ID <= LastGlobalConstantID;
39 }
40 bool isGlobalValue(unsigned ID) const {
41 return ID <= LastGlobalValueID && !isGlobalConstant(ID);
42 }
Duncan P. N. Exon Smith2e6a87b2014-07-29 23:03:40 +000043
44 unsigned size() const { return IDs.size(); }
45 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
46 std::pair<unsigned, bool> lookup(const Value *V) const {
47 return IDs.lookup(V);
48 }
Duncan P. N. Exon Smithba4576d2014-07-30 01:20:26 +000049 void index(const Value *V) {
50 // Explicitly sequence get-size and insert-value operations to avoid UB.
51 unsigned ID = IDs.size() + 1;
52 IDs[V].first = ID;
53 }
Duncan P. N. Exon Smith2e6a87b2014-07-29 23:03:40 +000054};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000055}
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +000056
57static void orderValue(const Value *V, OrderMap &OM) {
58 if (OM.lookup(V).first)
59 return;
60
61 if (const Constant *C = dyn_cast<Constant>(V))
62 if (C->getNumOperands() && !isa<GlobalValue>(C))
63 for (const Value *Op : C->operands())
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +000064 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +000065 orderValue(Op, OM);
66
67 // Note: we cannot cache this lookup above, since inserting into the map
Duncan P. N. Exon Smithba4576d2014-07-30 01:20:26 +000068 // changes the map's size, and thus affects the other IDs.
69 OM.index(V);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +000070}
71
Rafael Espindola49e9bf82014-11-17 20:06:27 +000072static OrderMap orderModule(const Module &M) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +000073 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
74 // and ValueEnumerator::incorporateFunction().
75 OrderMap OM;
76
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +000077 // In the reader, initializers of GlobalValues are set *after* all the
78 // globals have been read. Rather than awkwardly modeling this behaviour
79 // directly in predictValueUseListOrderImpl(), just assign IDs to
80 // initializers of GlobalValues before GlobalValues themselves to model this
81 // implicitly.
Rafael Espindola49e9bf82014-11-17 20:06:27 +000082 for (const GlobalVariable &G : M.globals())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +000083 if (G.hasInitializer())
Duncan P. N. Exon Smith91778672014-07-31 00:13:28 +000084 if (!isa<GlobalValue>(G.getInitializer()))
85 orderValue(G.getInitializer(), OM);
Rafael Espindola49e9bf82014-11-17 20:06:27 +000086 for (const GlobalAlias &A : M.aliases())
Duncan P. N. Exon Smith91778672014-07-31 00:13:28 +000087 if (!isa<GlobalValue>(A.getAliasee()))
88 orderValue(A.getAliasee(), OM);
Dmitry Polukhina1feff72016-04-07 12:32:19 +000089 for (const GlobalIFunc &I : M.ifuncs())
90 if (!isa<GlobalValue>(I.getResolver()))
91 orderValue(I.getResolver(), OM);
Peter Collingbourne51d2de72014-12-03 02:08:38 +000092 for (const Function &F : M) {
Vedant Kumar3a63fb32015-12-19 08:52:49 +000093 for (const Use &U : F.operands())
94 if (!isa<GlobalValue>(U.get()))
95 orderValue(U.get(), OM);
Peter Collingbourne51d2de72014-12-03 02:08:38 +000096 }
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +000097 OM.LastGlobalConstantID = OM.size();
98
99 // Initializers of GlobalValues are processed in
100 // BitcodeReader::ResolveGlobalAndAliasInits(). Match the order there rather
101 // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
102 // by giving IDs in reverse order.
103 //
104 // Since GlobalValues never reference each other directly (just through
105 // initializers), their relative IDs only matter for determining order of
106 // uses in their initializers.
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000107 for (const Function &F : M)
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +0000108 orderValue(&F, OM);
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000109 for (const GlobalAlias &A : M.aliases())
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +0000110 orderValue(&A, OM);
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000111 for (const GlobalIFunc &I : M.ifuncs())
112 orderValue(&I, OM);
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000113 for (const GlobalVariable &G : M.globals())
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +0000114 orderValue(&G, OM);
115 OM.LastGlobalValueID = OM.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000116
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000117 for (const Function &F : M) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000118 if (F.isDeclaration())
119 continue;
120 // Here we need to match the union of ValueEnumerator::incorporateFunction()
121 // and WriteFunction(). Basic blocks are implicitly declared before
122 // anything else (by declaring their size).
123 for (const BasicBlock &BB : F)
124 orderValue(&BB, OM);
125 for (const Argument &A : F.args())
126 orderValue(&A, OM);
127 for (const BasicBlock &BB : F)
128 for (const Instruction &I : BB)
129 for (const Value *Op : I.operands())
130 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
131 isa<InlineAsm>(*Op))
132 orderValue(Op, OM);
133 for (const BasicBlock &BB : F)
134 for (const Instruction &I : BB)
135 orderValue(&I, OM);
136 }
137 return OM;
138}
139
140static void predictValueUseListOrderImpl(const Value *V, const Function *F,
141 unsigned ID, const OrderMap &OM,
142 UseListOrderStack &Stack) {
143 // Predict use-list order for this one.
144 typedef std::pair<const Use *, unsigned> Entry;
145 SmallVector<Entry, 64> List;
146 for (const Use &U : V->uses())
147 // Check if this user will be serialized.
148 if (OM.lookup(U.getUser()).first)
149 List.push_back(std::make_pair(&U, List.size()));
150
151 if (List.size() < 2)
152 // We may have lost some users.
153 return;
154
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +0000155 bool IsGlobalValue = OM.isGlobalValue(ID);
156 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000157 const Use *LU = L.first;
158 const Use *RU = R.first;
Duncan P. N. Exon Smith3f0fc7b2014-07-29 01:13:56 +0000159 if (LU == RU)
160 return false;
161
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000162 auto LID = OM.lookup(LU->getUser()).first;
163 auto RID = OM.lookup(RU->getUser()).first;
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +0000164
165 // Global values are processed in reverse order.
166 //
167 // Moreover, initializers of GlobalValues are set *after* all the globals
168 // have been read (despite having earlier IDs). Rather than awkwardly
169 // modeling this behaviour here, orderModule() has assigned IDs to
170 // initializers of GlobalValues before GlobalValues themselves.
171 if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
172 return LID < RID;
173
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000174 // If ID is 4, then expect: 7 6 5 1 2 3.
175 if (LID < RID) {
Duncan P. N. Exon Smithab6adeb2014-07-31 18:33:12 +0000176 if (RID <= ID)
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +0000177 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
178 return true;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000179 return false;
180 }
181 if (RID < LID) {
Duncan P. N. Exon Smithab6adeb2014-07-31 18:33:12 +0000182 if (LID <= ID)
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +0000183 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
184 return false;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000185 return true;
186 }
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +0000187
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000188 // LID and RID are equal, so we have different operands of the same user.
189 // Assume operands are added in order for all instructions.
Duncan P. N. Exon Smithab6adeb2014-07-31 18:33:12 +0000190 if (LID <= ID)
Duncan P. N. Exon Smith3cbca202014-07-30 01:22:16 +0000191 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
192 return LU->getOperandNo() < RU->getOperandNo();
193 return LU->getOperandNo() > RU->getOperandNo();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000194 });
195
196 if (std::is_sorted(
197 List.begin(), List.end(),
198 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
199 // Order is already correct.
200 return;
201
202 // Store the shuffle.
Duncan P. N. Exon Smithd7a281a2014-07-29 16:58:18 +0000203 Stack.emplace_back(V, F, List.size());
204 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
Duncan P. N. Exon Smithf849ace2014-07-28 22:41:50 +0000205 for (size_t I = 0, E = List.size(); I != E; ++I)
Duncan P. N. Exon Smithd7a281a2014-07-29 16:58:18 +0000206 Stack.back().Shuffle[I] = List[I].second;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000207}
208
209static void predictValueUseListOrder(const Value *V, const Function *F,
210 OrderMap &OM, UseListOrderStack &Stack) {
211 auto &IDPair = OM[V];
212 assert(IDPair.first && "Unmapped value");
213 if (IDPair.second)
214 // Already predicted.
215 return;
216
217 // Do the actual prediction.
218 IDPair.second = true;
219 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
220 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
221
222 // Recursive descent into constants.
223 if (const Constant *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smithc69b5162014-07-30 17:51:09 +0000224 if (C->getNumOperands()) // Visit GlobalValues.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000225 for (const Value *Op : C->operands())
Duncan P. N. Exon Smithc69b5162014-07-30 17:51:09 +0000226 if (isa<Constant>(Op)) // Visit GlobalValues.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000227 predictValueUseListOrder(Op, F, OM, Stack);
228}
229
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000230static UseListOrderStack predictUseListOrder(const Module &M) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000231 OrderMap OM = orderModule(M);
232
233 // Use-list orders need to be serialized after all the users have been added
234 // to a value, or else the shuffles will be incomplete. Store them per
235 // function in a stack.
236 //
237 // Aside from function order, the order of values doesn't matter much here.
238 UseListOrderStack Stack;
239
240 // We want to visit the functions backward now so we can list function-local
241 // constants in the last Function they're used in. Module-level constants
242 // have already been visited above.
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000243 for (auto I = M.rbegin(), E = M.rend(); I != E; ++I) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000244 const Function &F = *I;
245 if (F.isDeclaration())
246 continue;
247 for (const BasicBlock &BB : F)
248 predictValueUseListOrder(&BB, &F, OM, Stack);
249 for (const Argument &A : F.args())
250 predictValueUseListOrder(&A, &F, OM, Stack);
251 for (const BasicBlock &BB : F)
252 for (const Instruction &I : BB)
253 for (const Value *Op : I.operands())
Duncan P. N. Exon Smithc69b5162014-07-30 17:51:09 +0000254 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000255 predictValueUseListOrder(Op, &F, OM, Stack);
256 for (const BasicBlock &BB : F)
257 for (const Instruction &I : BB)
258 predictValueUseListOrder(&I, &F, OM, Stack);
259 }
260
261 // Visit globals last, since the module-level use-list block will be seen
262 // before the function bodies are processed.
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000263 for (const GlobalVariable &G : M.globals())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000264 predictValueUseListOrder(&G, nullptr, OM, Stack);
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000265 for (const Function &F : M)
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000266 predictValueUseListOrder(&F, nullptr, OM, Stack);
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000267 for (const GlobalAlias &A : M.aliases())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000268 predictValueUseListOrder(&A, nullptr, OM, Stack);
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000269 for (const GlobalIFunc &I : M.ifuncs())
270 predictValueUseListOrder(&I, nullptr, OM, Stack);
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000271 for (const GlobalVariable &G : M.globals())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000272 if (G.hasInitializer())
273 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000274 for (const GlobalAlias &A : M.aliases())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000275 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000276 for (const GlobalIFunc &I : M.ifuncs())
277 predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
Peter Collingbourne51d2de72014-12-03 02:08:38 +0000278 for (const Function &F : M) {
Vedant Kumar3a63fb32015-12-19 08:52:49 +0000279 for (const Use &U : F.operands())
280 predictValueUseListOrder(U.get(), nullptr, OM, Stack);
Peter Collingbourne51d2de72014-12-03 02:08:38 +0000281 }
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000282
283 return Stack;
284}
285
Duncan Sandse6beec62012-11-13 12:59:33 +0000286static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
287 return V.first->getType()->isIntOrIntVectorTy();
Chris Lattner430e80d2007-05-04 05:21:47 +0000288}
289
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +0000290ValueEnumerator::ValueEnumerator(const Module &M,
291 bool ShouldPreserveUseListOrder)
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000292 : ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +0000293 if (ShouldPreserveUseListOrder)
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000294 UseListOrders = predictUseListOrder(M);
295
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000296 // Enumerate the global variables.
Yaron Keren4c20deb2015-06-12 20:18:20 +0000297 for (const GlobalVariable &GV : M.globals())
298 EnumerateValue(&GV);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000299
300 // Enumerate the functions.
Yaron Keren4c20deb2015-06-12 20:18:20 +0000301 for (const Function & F : M) {
302 EnumerateValue(&F);
303 EnumerateAttributes(F.getAttributes());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000304 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000305
Chris Lattner44c17072007-04-26 02:46:40 +0000306 // Enumerate the aliases.
Yaron Keren4c20deb2015-06-12 20:18:20 +0000307 for (const GlobalAlias &GA : M.aliases())
308 EnumerateValue(&GA);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000309
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000310 // Enumerate the ifuncs.
311 for (const GlobalIFunc &GIF : M.ifuncs())
312 EnumerateValue(&GIF);
313
Chris Lattner430e80d2007-05-04 05:21:47 +0000314 // Remember what is the cutoff between globalvalue's and other constants.
315 unsigned FirstConstant = Values.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000316
Javed Absarf3d79042017-05-11 12:28:08 +0000317 // Enumerate the global variable initializers and attributes.
318 for (const GlobalVariable &GV : M.globals()) {
Yaron Keren4c20deb2015-06-12 20:18:20 +0000319 if (GV.hasInitializer())
320 EnumerateValue(GV.getInitializer());
Javed Absarf3d79042017-05-11 12:28:08 +0000321 if (GV.hasAttributes())
322 EnumerateAttributes(GV.getAttributesAsList(AttributeList::FunctionIndex));
323 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000324
Chris Lattner44c17072007-04-26 02:46:40 +0000325 // Enumerate the aliasees.
Yaron Keren4c20deb2015-06-12 20:18:20 +0000326 for (const GlobalAlias &GA : M.aliases())
327 EnumerateValue(GA.getAliasee());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000328
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000329 // Enumerate the ifunc resolvers.
330 for (const GlobalIFunc &GIF : M.ifuncs())
331 EnumerateValue(GIF.getResolver());
332
Vedant Kumar3a63fb32015-12-19 08:52:49 +0000333 // Enumerate any optional Function data.
Yaron Keren4c20deb2015-06-12 20:18:20 +0000334 for (const Function &F : M)
Vedant Kumar3a63fb32015-12-19 08:52:49 +0000335 for (const Use &U : F.operands())
336 EnumerateValue(U.get());
David Majnemer7fddecc2015-06-17 20:52:32 +0000337
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000338 // Enumerate the metadata type.
339 //
340 // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
341 // only encodes the metadata type when it's used as a value.
342 EnumerateType(Type::getMetadataTy(M.getContext()));
343
Joe Abbeybc6f4ba2013-04-01 02:28:07 +0000344 // Insert constants and metadata that are named at module level into the slot
Devang Patelfcfee0f2010-01-07 19:39:36 +0000345 // pool so that the module symbol table can refer to them...
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000346 EnumerateValueSymbolTable(M.getValueSymbolTable());
Dan Gohman2637cc12010-07-21 23:38:33 +0000347 EnumerateNamedMetadata(M);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000348
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000349 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000350 for (const GlobalVariable &GV : M.globals()) {
Peter Collingbourne382d81c2016-06-01 01:17:57 +0000351 MDs.clear();
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000352 GV.getAllMetadata(MDs);
353 for (const auto &I : MDs)
Peter Collingbourne21521892016-06-21 23:42:48 +0000354 // FIXME: Pass GV to EnumerateMetadata and arrange for the bitcode writer
355 // to write metadata to the global variable's own metadata block
356 // (PR28134).
357 EnumerateMetadata(nullptr, I.second);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000358 }
Chris Lattner8dace892009-12-31 00:51:46 +0000359
Chris Lattner5f640b92007-04-26 03:50:57 +0000360 // Enumerate types used by function bodies and argument lists.
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000361 for (const Function &F : M) {
Rafael Espindola087d6272014-06-17 03:00:40 +0000362 for (const Argument &A : F.args())
363 EnumerateType(A.getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000364
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000365 // Enumerate metadata attached to this function.
Peter Collingbourne382d81c2016-06-01 01:17:57 +0000366 MDs.clear();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000367 F.getAllMetadata(MDs);
368 for (const auto &I : MDs)
Peter Collingbourne21521892016-06-21 23:42:48 +0000369 EnumerateMetadata(F.isDeclaration() ? nullptr : &F, I.second);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000370
Rafael Espindola087d6272014-06-17 03:00:40 +0000371 for (const BasicBlock &BB : F)
372 for (const Instruction &I : BB) {
373 for (const Use &Op : I.operands()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000374 auto *MD = dyn_cast<MetadataAsValue>(&Op);
375 if (!MD) {
376 EnumerateOperandType(Op);
377 continue;
378 }
379
380 // Local metadata is enumerated during function-incorporation.
381 if (isa<LocalAsMetadata>(MD->getMetadata()))
382 continue;
383
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000384 EnumerateMetadata(&F, MD->getMetadata());
Victor Hernandez572218b2010-01-14 19:54:11 +0000385 }
Rafael Espindola087d6272014-06-17 03:00:40 +0000386 EnumerateType(I.getType());
387 if (const CallInst *CI = dyn_cast<CallInst>(&I))
Devang Patel4c758ea2008-09-25 21:00:45 +0000388 EnumerateAttributes(CI->getAttributes());
Rafael Espindola087d6272014-06-17 03:00:40 +0000389 else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
Devang Patel4c758ea2008-09-25 21:00:45 +0000390 EnumerateAttributes(II->getAttributes());
Devang Patelaf206b82009-09-18 19:26:43 +0000391
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000392 // Enumerate metadata attached with this instruction.
Devang Patel6da5dbf2009-10-22 18:55:16 +0000393 MDs.clear();
Rafael Espindola087d6272014-06-17 03:00:40 +0000394 I.getAllMetadataOtherThanDebugLoc(MDs);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000395 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000396 EnumerateMetadata(&F, MDs[i].second);
Joe Abbey2ad8df22012-11-25 15:23:39 +0000397
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +0000398 // Don't enumerate the location directly -- it has a special record
399 // type -- but enumerate its operands.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000400 if (DILocation *L = I.getDebugLoc())
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000401 for (const Metadata *Op : L->operands())
402 EnumerateMetadata(&F, Op);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000403 }
404 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000405
Chris Lattner430e80d2007-05-04 05:21:47 +0000406 // Optimize constant ordering.
407 OptimizeConstants(FirstConstant, Values.size());
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000408
409 // Organize metadata ordering.
410 organizeMetadata();
Rafael Espindola337a1b22011-04-06 16:49:37 +0000411}
412
Devang Patelaf206b82009-09-18 19:26:43 +0000413unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
414 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000415 assert(I != InstructionMap.end() && "Instruction is not mapped!");
Dan Gohman1f4b0282010-08-25 17:09:50 +0000416 return I->second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000417}
Devang Patelaf206b82009-09-18 19:26:43 +0000418
David Majnemerdad0a642014-06-27 18:19:56 +0000419unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
420 unsigned ComdatID = Comdats.idFor(C);
421 assert(ComdatID && "Comdat not found!");
422 return ComdatID;
423}
424
Devang Patelaf206b82009-09-18 19:26:43 +0000425void ValueEnumerator::setInstructionID(const Instruction *I) {
426 InstructionMap[I] = InstructionCount++;
427}
428
Devang Patel05eb6172009-08-04 06:00:18 +0000429unsigned ValueEnumerator::getValueID(const Value *V) const {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000430 if (auto *MD = dyn_cast<MetadataAsValue>(V))
431 return getMetadataID(MD->getMetadata());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000432
Devang Patel05eb6172009-08-04 06:00:18 +0000433 ValueMapType::const_iterator I = ValueMap.find(V);
434 assert(I != ValueMap.end() && "Value not in slotcalculator!");
435 return I->second-1;
436}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000437
Matthias Braun8c209aa2017-01-28 02:02:38 +0000438#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +0000439LLVM_DUMP_METHOD void ValueEnumerator::dump() const {
Chad Rosier78037a92011-12-07 20:44:46 +0000440 print(dbgs(), ValueMap, "Default");
441 dbgs() << '\n';
Teresa Johnson61b406e2015-12-29 23:00:22 +0000442 print(dbgs(), MetadataMap, "MetaData");
Chad Rosier78037a92011-12-07 20:44:46 +0000443 dbgs() << '\n';
444}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000445#endif
Chad Rosier78037a92011-12-07 20:44:46 +0000446
447void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
448 const char *Name) const {
449
450 OS << "Map Name: " << Name << "\n";
451 OS << "Size: " << Map.size() << "\n";
452 for (ValueMapType::const_iterator I = Map.begin(),
453 E = Map.end(); I != E; ++I) {
454
455 const Value *V = I->first;
456 if (V->hasName())
457 OS << "Value: " << V->getName();
458 else
459 OS << "Value: [null]\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +0000460 V->print(errs());
461 errs() << '\n';
Chad Rosier78037a92011-12-07 20:44:46 +0000462
463 OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
Chandler Carruthcdf47882014-03-09 03:16:01 +0000464 for (const Use &U : V->uses()) {
465 if (&U != &*V->use_begin())
Chad Rosier78037a92011-12-07 20:44:46 +0000466 OS << ",";
Chandler Carruthcdf47882014-03-09 03:16:01 +0000467 if(U->hasName())
468 OS << " " << U->getName();
Chad Rosier78037a92011-12-07 20:44:46 +0000469 else
470 OS << " [null]";
471
472 }
473 OS << "\n\n";
474 }
475}
476
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000477void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
478 const char *Name) const {
479
480 OS << "Map Name: " << Name << "\n";
481 OS << "Size: " << Map.size() << "\n";
482 for (auto I = Map.begin(), E = Map.end(); I != E; ++I) {
483 const Metadata *MD = I->first;
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000484 OS << "Metadata: slot = " << I->second.ID << "\n";
485 OS << "Metadata: function = " << I->second.F << "\n";
Nick Lewyckyee0a3a72014-12-17 01:52:08 +0000486 MD->print(OS);
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000487 OS << "\n";
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000488 }
489}
490
Chris Lattner430e80d2007-05-04 05:21:47 +0000491/// OptimizeConstants - Reorder constant pool for denser encoding.
492void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
493 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000494
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +0000495 if (ShouldPreserveUseListOrder)
Duncan P. N. Exon Smith15eb0ab2014-07-25 16:13:16 +0000496 // Optimizing constants makes the use-list order difficult to predict.
497 // Disable it for now when trying to preserve the order.
498 return;
499
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000500 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
501 [this](const std::pair<const Value *, unsigned> &LHS,
502 const std::pair<const Value *, unsigned> &RHS) {
503 // Sort by plane.
504 if (LHS.first->getType() != RHS.first->getType())
505 return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
506 // Then by frequency.
507 return LHS.second > RHS.second;
508 });
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000509
Duncan Sandse6beec62012-11-13 12:59:33 +0000510 // Ensure that integer and vector of integer constants are at the start of the
511 // constant pool. This is important so that GEP structure indices come before
512 // gep constant exprs.
Duncan P. N. Exon Smithbdde9e12016-03-25 02:20:28 +0000513 std::stable_partition(Values.begin() + CstStart, Values.begin() + CstEnd,
514 isIntOrIntVectorValue);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000515
Chris Lattner430e80d2007-05-04 05:21:47 +0000516 // Rebuild the modified portion of ValueMap.
517 for (; CstStart != CstEnd; ++CstStart)
518 ValueMap[Values[CstStart].first] = CstStart+1;
519}
520
521
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000522/// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
523/// table into the values table.
524void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000525 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000526 VI != VE; ++VI)
527 EnumerateValue(VI->getValue());
528}
529
Rafael Espindola49e9bf82014-11-17 20:06:27 +0000530/// Insert all of the values referenced by named metadata in the specified
531/// module.
532void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +0000533 for (const auto &I : M.named_metadata())
534 EnumerateNamedMDNode(&I);
Devang Patelfcfee0f2010-01-07 19:39:36 +0000535}
536
Devang Patel99ff5a82010-01-09 00:30:14 +0000537void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
Devang Patel99ff5a82010-01-09 00:30:14 +0000538 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000539 EnumerateMetadata(nullptr, MD->getOperand(i));
540}
541
Peter Collingbourne21521892016-06-21 23:42:48 +0000542unsigned ValueEnumerator::getMetadataFunctionID(const Function *F) const {
543 return F ? getValueID(F) + 1 : 0;
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000544}
545
Peter Collingbourne21521892016-06-21 23:42:48 +0000546void ValueEnumerator::EnumerateMetadata(const Function *F, const Metadata *MD) {
547 EnumerateMetadata(getMetadataFunctionID(F), MD);
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000548}
549
550void ValueEnumerator::EnumerateFunctionLocalMetadata(
551 const Function &F, const LocalAsMetadata *Local) {
Peter Collingbourne21521892016-06-21 23:42:48 +0000552 EnumerateFunctionLocalMetadata(getMetadataFunctionID(&F), Local);
Devang Patel99ff5a82010-01-09 00:30:14 +0000553}
554
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000555void ValueEnumerator::dropFunctionFromMetadata(
556 MetadataMapType::value_type &FirstMD) {
Duncan P. N. Exon Smith134cb5d2016-04-18 01:24:58 +0000557 SmallVector<const MDNode *, 64> Worklist;
Malcolm Parsons17d266b2017-01-13 17:12:16 +0000558 auto push = [&Worklist](MetadataMapType::value_type &MD) {
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000559 auto &Entry = MD.second;
560
561 // Nothing to do if this metadata isn't tagged.
562 if (!Entry.F)
563 return;
564
565 // Drop the function tag.
566 Entry.F = 0;
567
568 // If this is has an ID and is an MDNode, then its operands have entries as
569 // well. We need to drop the function from them too.
570 if (Entry.ID)
571 if (auto *N = dyn_cast<MDNode>(MD.first))
572 Worklist.push_back(N);
573 };
574 push(FirstMD);
575 while (!Worklist.empty())
Duncan P. N. Exon Smith134cb5d2016-04-18 01:24:58 +0000576 for (const Metadata *Op : Worklist.pop_back_val()->operands()) {
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000577 if (!Op)
578 continue;
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000579 auto MD = MetadataMap.find(Op);
580 if (MD != MetadataMap.end())
581 push(*MD);
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000582 }
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000583}
584
585void ValueEnumerator::EnumerateMetadata(unsigned F, const Metadata *MD) {
Duncan P. N. Exon Smith30805b22016-04-23 04:59:22 +0000586 // It's vital for reader efficiency that uniqued subgraphs are done in
587 // post-order; it's expensive when their operands have forward references.
588 // If a distinct node is referenced from a uniqued node, it'll be delayed
589 // until the uniqued subgraph has been completely traversed.
590 SmallVector<const MDNode *, 32> DelayedDistinctNodes;
591
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000592 // Start by enumerating MD, and then work through its transitive operands in
Duncan P. N. Exon Smithc1965312016-04-21 01:55:12 +0000593 // post-order. This requires a depth-first search.
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000594 SmallVector<std::pair<const MDNode *, MDNode::op_iterator>, 32> Worklist;
595 if (const MDNode *N = enumerateMetadataImpl(F, MD))
596 Worklist.push_back(std::make_pair(N, N->op_begin()));
597
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000598 while (!Worklist.empty()) {
599 const MDNode *N = Worklist.back().first;
Duncan P. N. Exon Smithc1965312016-04-21 01:55:12 +0000600
Duncan P. N. Exon Smithd9bbdce2016-04-23 04:22:38 +0000601 // Enumerate operands until we hit a new node. We need to traverse these
602 // nodes' operands before visiting the rest of N's operands.
603 MDNode::op_iterator I = std::find_if(
604 Worklist.back().second, N->op_end(),
605 [&](const Metadata *MD) { return enumerateMetadataImpl(F, MD); });
606 if (I != N->op_end()) {
607 auto *Op = cast<MDNode>(*I);
608 Worklist.back().second = ++I;
Duncan P. N. Exon Smith30805b22016-04-23 04:59:22 +0000609
610 // Delay traversing Op if it's a distinct node and N is uniqued.
611 if (Op->isDistinct() && !N->isDistinct())
612 DelayedDistinctNodes.push_back(Op);
613 else
614 Worklist.push_back(std::make_pair(Op, Op->op_begin()));
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000615 continue;
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000616 }
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000617
618 // All the operands have been visited. Now assign an ID.
619 Worklist.pop_back();
620 MDs.push_back(N);
621 MetadataMap[N].ID = MDs.size();
Duncan P. N. Exon Smith30805b22016-04-23 04:59:22 +0000622
623 // Flush out any delayed distinct nodes; these are all the distinct nodes
624 // that are leaves in last uniqued subgraph.
625 if (Worklist.empty() || Worklist.back().first->isDistinct()) {
626 for (const MDNode *N : DelayedDistinctNodes)
627 Worklist.push_back(std::make_pair(N, N->op_begin()));
628 DelayedDistinctNodes.clear();
629 }
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000630 }
631}
632
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000633const MDNode *ValueEnumerator::enumerateMetadataImpl(unsigned F, const Metadata *MD) {
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000634 if (!MD)
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000635 return nullptr;
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000636
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000637 assert(
638 (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
639 "Invalid metadata kind");
Dan Gohmanc828c542010-08-24 02:24:03 +0000640
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000641 auto Insertion = MetadataMap.insert(std::make_pair(MD, MDIndex(F)));
642 MDIndex &Entry = Insertion.first->second;
643 if (!Insertion.second) {
644 // Already mapped. If F doesn't match the function tag, drop it.
645 if (Entry.hasDifferentFunction(F))
646 dropFunctionFromMetadata(*Insertion.first);
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000647 return nullptr;
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000648 }
Duncan P. N. Exon Smith60d87e72014-10-21 22:13:34 +0000649
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000650 // Don't assign IDs to metadata nodes.
651 if (auto *N = dyn_cast<MDNode>(MD))
652 return N;
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +0000653
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000654 // Save the metadata.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000655 MDs.push_back(MD);
Duncan P. N. Exon Smith9695eb32016-04-19 03:46:51 +0000656 Entry.ID = MDs.size();
657
658 // Enumerate the constant, if any.
659 if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
660 EnumerateValue(C->getValue());
Duncan P. N. Exon Smithc1965312016-04-21 01:55:12 +0000661
Duncan P. N. Exon Smith71480bd2016-04-22 02:33:06 +0000662 return nullptr;
Dan Gohmanc828c542010-08-24 02:24:03 +0000663}
664
665/// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000666/// information reachable from the metadata.
667void ValueEnumerator::EnumerateFunctionLocalMetadata(
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000668 unsigned F, const LocalAsMetadata *Local) {
669 assert(F && "Expected a function");
670
Dan Gohmanc828c542010-08-24 02:24:03 +0000671 // Check to see if it's already in!
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000672 MDIndex &Index = MetadataMap[Local];
673 if (Index.ID) {
674 assert(Index.F == F && "Expected the same function");
Dan Gohmanc828c542010-08-24 02:24:03 +0000675 return;
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000676 }
Duncan P. N. Exon Smith60d87e72014-10-21 22:13:34 +0000677
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000678 MDs.push_back(Local);
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000679 Index.F = F;
680 Index.ID = MDs.size();
Dan Gohmanc828c542010-08-24 02:24:03 +0000681
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000682 EnumerateValue(Local->getValue());
Devang Patel05eb6172009-08-04 06:00:18 +0000683}
684
Duncan P. N. Exon Smith1483fff2016-04-23 04:42:39 +0000685static unsigned getMetadataTypeOrder(const Metadata *MD) {
686 // Strings are emitted in bulk and must come first.
687 if (isa<MDString>(MD))
688 return 0;
689
690 // ConstantAsMetadata doesn't reference anything. We may as well shuffle it
691 // to the front since we can detect it.
692 auto *N = dyn_cast<MDNode>(MD);
693 if (!N)
694 return 1;
695
696 // The reader is fast forward references for distinct node operands, but slow
697 // when uniqued operands are unresolved.
698 return N->isDistinct() ? 2 : 3;
699}
700
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000701void ValueEnumerator::organizeMetadata() {
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000702 assert(MetadataMap.size() == MDs.size() &&
703 "Metadata map and vector out of sync");
704
705 if (MDs.empty())
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000706 return;
707
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000708 // Copy out the index information from MetadataMap in order to choose a new
709 // order.
710 SmallVector<MDIndex, 64> Order;
711 Order.reserve(MetadataMap.size());
712 for (const Metadata *MD : MDs)
713 Order.push_back(MetadataMap.lookup(MD));
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000714
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000715 // Partition:
716 // - by function, then
717 // - by isa<MDString>
718 // and then sort by the original/current ID. Since the IDs are guaranteed to
719 // be unique, the result of std::sort will be deterministic. There's no need
720 // for std::stable_sort.
721 std::sort(Order.begin(), Order.end(), [this](MDIndex LHS, MDIndex RHS) {
Duncan P. N. Exon Smith1483fff2016-04-23 04:42:39 +0000722 return std::make_tuple(LHS.F, getMetadataTypeOrder(LHS.get(MDs)), LHS.ID) <
723 std::make_tuple(RHS.F, getMetadataTypeOrder(RHS.get(MDs)), RHS.ID);
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000724 });
725
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000726 // Rebuild MDs, index the metadata ranges for each function in FunctionMDs,
727 // and fix up MetadataMap.
728 std::vector<const Metadata *> OldMDs = std::move(MDs);
729 MDs.reserve(OldMDs.size());
730 for (unsigned I = 0, E = Order.size(); I != E && !Order[I].F; ++I) {
731 auto *MD = Order[I].get(OldMDs);
732 MDs.push_back(MD);
733 MetadataMap[MD].ID = I + 1;
734 if (isa<MDString>(MD))
735 ++NumMDStrings;
736 }
737
738 // Return early if there's nothing for the functions.
739 if (MDs.size() == Order.size())
740 return;
741
742 // Build the function metadata ranges.
743 MDRange R;
744 FunctionMDs.reserve(OldMDs.size());
745 unsigned PrevF = 0;
746 for (unsigned I = MDs.size(), E = Order.size(), ID = MDs.size(); I != E;
747 ++I) {
748 unsigned F = Order[I].F;
749 if (!PrevF) {
750 PrevF = F;
751 } else if (PrevF != F) {
752 R.Last = FunctionMDs.size();
753 std::swap(R, FunctionMDInfo[PrevF]);
754 R.First = FunctionMDs.size();
755
756 ID = MDs.size();
757 PrevF = F;
758 }
759
760 auto *MD = Order[I].get(OldMDs);
761 FunctionMDs.push_back(MD);
762 MetadataMap[MD].ID = ++ID;
763 if (isa<MDString>(MD))
764 ++R.NumStrings;
765 }
766 R.Last = FunctionMDs.size();
767 FunctionMDInfo[PrevF] = R;
768}
769
770void ValueEnumerator::incorporateFunctionMetadata(const Function &F) {
771 NumModuleMDs = MDs.size();
772
773 auto R = FunctionMDInfo.lookup(getValueID(&F) + 1);
774 NumMDStrings = R.NumStrings;
775 MDs.insert(MDs.end(), FunctionMDs.begin() + R.First,
776 FunctionMDs.begin() + R.Last);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000777}
778
Victor Hernandez572218b2010-01-14 19:54:11 +0000779void ValueEnumerator::EnumerateValue(const Value *V) {
Chris Lattner8dace892009-12-31 00:51:46 +0000780 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000781 assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
Devang Patel05eb6172009-08-04 06:00:18 +0000782
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000783 // Check to see if it's already in!
784 unsigned &ValueID = ValueMap[V];
785 if (ValueID) {
786 // Increment use count.
787 Values[ValueID-1].second++;
788 return;
789 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000790
David Majnemerdad0a642014-06-27 18:19:56 +0000791 if (auto *GO = dyn_cast<GlobalObject>(V))
792 if (const Comdat *C = GO->getComdat())
793 Comdats.insert(C);
794
Chris Lattner9ee48362007-05-06 01:00:28 +0000795 // Enumerate the type of this value.
796 EnumerateType(V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000797
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000798 if (const Constant *C = dyn_cast<Constant>(V)) {
799 if (isa<GlobalValue>(C)) {
800 // Initializers for globals are handled explicitly elsewhere.
Chris Lattner9ee48362007-05-06 01:00:28 +0000801 } else if (C->getNumOperands()) {
802 // If a constant has operands, enumerate them. This makes sure that if a
803 // constant has uses (for example an array of const ints), that they are
804 // inserted also.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000805
Chris Lattner9ee48362007-05-06 01:00:28 +0000806 // We prefer to enumerate them with values before we enumerate the user
807 // itself. This makes it more likely that we can avoid forward references
808 // in the reader. We know that there can be no cycles in the constants
809 // graph that don't go through a global variable.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000810 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
811 I != E; ++I)
Chris Lattneraa99c942009-11-01 01:27:45 +0000812 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
Victor Hernandez572218b2010-01-14 19:54:11 +0000813 EnumerateValue(*I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000814
Chris Lattner9ee48362007-05-06 01:00:28 +0000815 // Finally, add the value. Doing this could make the ValueID reference be
816 // dangling, don't reuse it.
817 Values.push_back(std::make_pair(V, 1U));
818 ValueMap[V] = Values.size();
819 return;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000820 }
821 }
Devang Patele059ba6e2009-07-23 01:07:34 +0000822
Chris Lattner9ee48362007-05-06 01:00:28 +0000823 // Add the value.
824 Values.push_back(std::make_pair(V, 1U));
825 ValueID = Values.size();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000826}
827
828
Chris Lattner229907c2011-07-18 04:54:35 +0000829void ValueEnumerator::EnumerateType(Type *Ty) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000830 unsigned *TypeID = &TypeMap[Ty];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000831
Rafael Espindola337a1b22011-04-06 16:49:37 +0000832 // We've already seen this type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000833 if (*TypeID)
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000834 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000835
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000836 // If it is a non-anonymous struct, mark the type as being visited so that we
837 // don't recursively visit it. This is safe because we allow forward
838 // references of these in the bitcode reader.
Chris Lattner229907c2011-07-18 04:54:35 +0000839 if (StructType *STy = dyn_cast<StructType>(Ty))
Chris Lattner335d3992011-08-12 18:06:37 +0000840 if (!STy->isLiteral())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000841 *TypeID = ~0U;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000842
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000843 // Enumerate all of the subtypes before we enumerate this type. This ensures
844 // that the type will be enumerated in an order that can be directly built.
Rafael Espindolaffbfcf22014-11-24 20:44:36 +0000845 for (Type *SubTy : Ty->subtypes())
846 EnumerateType(SubTy);
Joe Abbey2ad8df22012-11-25 15:23:39 +0000847
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000848 // Refresh the TypeID pointer in case the table rehashed.
849 TypeID = &TypeMap[Ty];
Joe Abbey2ad8df22012-11-25 15:23:39 +0000850
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000851 // Check to see if we got the pointer another way. This can happen when
852 // enumerating recursive types that hit the base case deeper than they start.
853 //
854 // If this is actually a struct that we are treating as forward ref'able,
855 // then emit the definition now that all of its contents are available.
856 if (*TypeID && *TypeID != ~0U)
857 return;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000858
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000859 // Add this type now that its contents are all happily enumerated.
860 Types.push_back(Ty);
Joe Abbey2ad8df22012-11-25 15:23:39 +0000861
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000862 *TypeID = Types.size();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000863}
864
Chris Lattner76fd90f2007-05-06 08:35:19 +0000865// Enumerate the types for the specified value. If the value is a constant,
866// walk through it, enumerating the types of the constant.
Victor Hernandez572218b2010-01-14 19:54:11 +0000867void ValueEnumerator::EnumerateOperandType(const Value *V) {
Chris Lattner76fd90f2007-05-06 08:35:19 +0000868 EnumerateType(V->getType());
Joe Abbey2ad8df22012-11-25 15:23:39 +0000869
Duncan P. N. Exon Smith544e4f92016-03-28 00:03:12 +0000870 assert(!isa<MetadataAsValue>(V) && "Unexpected metadata operand");
Joe Abbey2ad8df22012-11-25 15:23:39 +0000871
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000872 const Constant *C = dyn_cast<Constant>(V);
873 if (!C)
874 return;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000875
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000876 // If this constant is already enumerated, ignore it, we know its type must
877 // be enumerated.
878 if (ValueMap.count(C))
879 return;
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000880
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000881 // This constant may have operands, make sure to enumerate the types in
882 // them.
Pete Cooper125ad172015-06-25 20:51:38 +0000883 for (const Value *Op : C->operands()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000884 // Don't enumerate basic blocks here, this happens as operands to
885 // blockaddress.
886 if (isa<BasicBlock>(Op))
887 continue;
888
889 EnumerateOperandType(Op);
890 }
Chris Lattner76fd90f2007-05-06 08:35:19 +0000891}
892
Reid Klecknerb5180542017-03-21 16:57:19 +0000893void ValueEnumerator::EnumerateAttributes(AttributeList PAL) {
Chris Lattner8a923e72008-03-12 17:45:29 +0000894 if (PAL.isEmpty()) return; // null is always 0.
Bill Wendling7b5f4f32013-02-12 08:01:22 +0000895
Chris Lattnere4bbad62007-05-03 22:46:43 +0000896 // Do a lookup.
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000897 unsigned &Entry = AttributeListMap[PAL];
Chris Lattnere4bbad62007-05-03 22:46:43 +0000898 if (Entry == 0) {
899 // Never saw this before, add it.
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000900 AttributeLists.push_back(PAL);
901 Entry = AttributeLists.size();
Chris Lattnere4bbad62007-05-03 22:46:43 +0000902 }
Bill Wendling51f612e2013-02-10 23:06:02 +0000903
904 // Do lookups for all attribute groups.
Reid Kleckner8bf67fe2017-05-23 17:01:48 +0000905 for (unsigned i = PAL.index_begin(), e = PAL.index_end(); i != e; ++i) {
906 AttributeSet AS = PAL.getAttributes(i);
907 if (!AS.hasAttributes())
908 continue;
909 IndexAndAttrSet Pair = {i, AS};
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000910 unsigned &Entry = AttributeGroupMap[Pair];
Bill Wendling51f612e2013-02-10 23:06:02 +0000911 if (Entry == 0) {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000912 AttributeGroups.push_back(Pair);
Bill Wendling92ed7002013-02-11 22:33:26 +0000913 Entry = AttributeGroups.size();
Bill Wendling51f612e2013-02-10 23:06:02 +0000914 }
915 }
Chris Lattnere4bbad62007-05-03 22:46:43 +0000916}
917
Chad Rosier6a11b642011-06-03 17:02:19 +0000918void ValueEnumerator::incorporateFunction(const Function &F) {
Nick Lewyckya72e1af2010-02-25 08:30:17 +0000919 InstructionCount = 0;
Chris Lattnere6e364c2007-04-26 05:53:54 +0000920 NumModuleValues = Values.size();
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000921
922 // Add global metadata to the function block. This doesn't include
923 // LocalAsMetadata.
924 incorporateFunctionMetadata(F);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000925
Chris Lattner5f640b92007-04-26 03:50:57 +0000926 // Adding function arguments to the value table.
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +0000927 for (const auto &I : F.args())
928 EnumerateValue(&I);
Chris Lattner5f640b92007-04-26 03:50:57 +0000929
Chris Lattnere6e364c2007-04-26 05:53:54 +0000930 FirstFuncConstantID = Values.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000931
Chris Lattner5f640b92007-04-26 03:50:57 +0000932 // Add all function-level constants to the value table.
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +0000933 for (const BasicBlock &BB : F) {
934 for (const Instruction &I : BB)
935 for (const Use &OI : I.operands()) {
936 if ((isa<Constant>(OI) && !isa<GlobalValue>(OI)) || isa<InlineAsm>(OI))
937 EnumerateValue(OI);
Chris Lattner5f640b92007-04-26 03:50:57 +0000938 }
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +0000939 BasicBlocks.push_back(&BB);
940 ValueMap[&BB] = BasicBlocks.size();
Chris Lattner5f640b92007-04-26 03:50:57 +0000941 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000942
Chris Lattner430e80d2007-05-04 05:21:47 +0000943 // Optimize the constant layout.
944 OptimizeConstants(FirstFuncConstantID, Values.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000945
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000946 // Add the function's parameter attributes so they are available for use in
947 // the function's instruction.
Devang Patel4c758ea2008-09-25 21:00:45 +0000948 EnumerateAttributes(F.getAttributes());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000949
Chris Lattnere6e364c2007-04-26 05:53:54 +0000950 FirstInstID = Values.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000951
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000952 SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
Chris Lattner5f640b92007-04-26 03:50:57 +0000953 // Add all of the instructions.
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +0000954 for (const BasicBlock &BB : F) {
955 for (const Instruction &I : BB) {
956 for (const Use &OI : I.operands()) {
957 if (auto *MD = dyn_cast<MetadataAsValue>(&OI))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000958 if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata()))
Victor Hernandezd44ee352010-02-04 01:13:08 +0000959 // Enumerate metadata after the instructions they might refer to.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000960 FnLocalMDVector.push_back(Local);
Dan Gohmanc828c542010-08-24 02:24:03 +0000961 }
Joe Abbey2ad8df22012-11-25 15:23:39 +0000962
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +0000963 if (!I.getType()->isVoidTy())
964 EnumerateValue(&I);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000965 }
966 }
Victor Hernandezd44ee352010-02-04 01:13:08 +0000967
968 // Add all of the function-local metadata.
Mehdi Aminia5cbf432016-07-08 01:13:41 +0000969 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i) {
970 // At this point, every local values have been incorporated, we shouldn't
971 // have a metadata operand that references a value that hasn't been seen.
972 assert(ValueMap.count(FnLocalMDVector[i]->getValue()) &&
973 "Missing value for metadata operand");
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000974 EnumerateFunctionLocalMetadata(F, FnLocalMDVector[i]);
Mehdi Aminia5cbf432016-07-08 01:13:41 +0000975 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000976}
977
Chad Rosier6a11b642011-06-03 17:02:19 +0000978void ValueEnumerator::purgeFunction() {
Chris Lattner5f640b92007-04-26 03:50:57 +0000979 /// Remove purged values from the ValueMap.
Chris Lattnere6e364c2007-04-26 05:53:54 +0000980 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
Chris Lattner5f640b92007-04-26 03:50:57 +0000981 ValueMap.erase(Values[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000982 for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
Teresa Johnson61b406e2015-12-29 23:00:22 +0000983 MetadataMap.erase(MDs[i]);
Chris Lattner7c37b012007-04-26 04:42:16 +0000984 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
985 ValueMap.erase(BasicBlocks[i]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000986
Chris Lattnere6e364c2007-04-26 05:53:54 +0000987 Values.resize(NumModuleValues);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000988 MDs.resize(NumModuleMDs);
Chris Lattner7c37b012007-04-26 04:42:16 +0000989 BasicBlocks.clear();
Duncan P. N. Exon Smith520f8542016-04-02 15:22:57 +0000990 NumMDStrings = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000991}
Chris Lattnerf540d742009-10-28 05:24:40 +0000992
993static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
994 DenseMap<const BasicBlock*, unsigned> &IDMap) {
995 unsigned Counter = 0;
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +0000996 for (const BasicBlock &BB : *F)
997 IDMap[&BB] = ++Counter;
Chris Lattnerf540d742009-10-28 05:24:40 +0000998}
999
1000/// getGlobalBasicBlockID - This returns the function-specific ID for the
1001/// specified basic block. This is relatively expensive information, so it
1002/// should only be used by rare constructs such as address-of-label.
1003unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
1004 unsigned &Idx = GlobalBasicBlockIDs[BB];
1005 if (Idx != 0)
Chris Lattneraa99c942009-11-01 01:27:45 +00001006 return Idx-1;
Chris Lattnerf540d742009-10-28 05:24:40 +00001007
1008 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
1009 return getGlobalBasicBlockID(BB);
1010}
David Blaikie7b028102015-02-25 00:51:52 +00001011
1012uint64_t ValueEnumerator::computeBitsRequiredForTypeIndicies() const {
1013 return Log2_32_Ceil(getTypes().size() + 1);
1014}