blob: 273ea06c641df30bca62890faf39650af2472ab6 [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"
18#include "llvm/IR/DerivedTypes.h"
19#include "llvm/IR/Instructions.h"
20#include "llvm/IR/Module.h"
Duncan P. N. Exon Smith15eb0ab2014-07-25 16:13:16 +000021#include "llvm/IR/UseListOrder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/ValueSymbolTable.h"
Chad Rosier78037a92011-12-07 20:44:46 +000023#include "llvm/Support/Debug.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattnera8713be2007-05-04 05:05:48 +000025#include <algorithm>
Chris Lattnerc1d10d62007-04-22 06:24:45 +000026using namespace llvm;
27
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +000028namespace {
29typedef DenseMap<const Value *, std::pair<unsigned, bool>> OrderMap;
30}
31
32static void orderValue(const Value *V, OrderMap &OM) {
33 if (OM.lookup(V).first)
34 return;
35
36 if (const Constant *C = dyn_cast<Constant>(V))
37 if (C->getNumOperands() && !isa<GlobalValue>(C))
38 for (const Value *Op : C->operands())
39 if (!isa<BasicBlock>(Op))
40 orderValue(Op, OM);
41
42 // Note: we cannot cache this lookup above, since inserting into the map
43 // changes the map's size, and thus affects the ID.
44 OM[V].first = OM.size() + 1;
45}
46
47static OrderMap orderModule(const Module *M) {
48 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
49 // and ValueEnumerator::incorporateFunction().
50 OrderMap OM;
51
52 for (const GlobalVariable &G : M->globals())
53 orderValue(&G, OM);
54 for (const Function &F : *M)
55 orderValue(&F, OM);
56 for (const GlobalAlias &A : M->aliases())
57 orderValue(&A, OM);
58 for (const GlobalVariable &G : M->globals())
59 if (G.hasInitializer())
60 orderValue(G.getInitializer(), OM);
61 for (const GlobalAlias &A : M->aliases())
62 orderValue(A.getAliasee(), OM);
63 for (const Function &F : *M)
64 if (F.hasPrefixData())
65 orderValue(F.getPrefixData(), OM);
66
67 for (const Function &F : *M) {
68 if (F.isDeclaration())
69 continue;
70 // Here we need to match the union of ValueEnumerator::incorporateFunction()
71 // and WriteFunction(). Basic blocks are implicitly declared before
72 // anything else (by declaring their size).
73 for (const BasicBlock &BB : F)
74 orderValue(&BB, OM);
75 for (const Argument &A : F.args())
76 orderValue(&A, OM);
77 for (const BasicBlock &BB : F)
78 for (const Instruction &I : BB)
79 for (const Value *Op : I.operands())
80 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
81 isa<InlineAsm>(*Op))
82 orderValue(Op, OM);
83 for (const BasicBlock &BB : F)
84 for (const Instruction &I : BB)
85 orderValue(&I, OM);
86 }
87 return OM;
88}
89
90static void predictValueUseListOrderImpl(const Value *V, const Function *F,
91 unsigned ID, const OrderMap &OM,
92 UseListOrderStack &Stack) {
93 // Predict use-list order for this one.
94 typedef std::pair<const Use *, unsigned> Entry;
95 SmallVector<Entry, 64> List;
96 for (const Use &U : V->uses())
97 // Check if this user will be serialized.
98 if (OM.lookup(U.getUser()).first)
99 List.push_back(std::make_pair(&U, List.size()));
100
101 if (List.size() < 2)
102 // We may have lost some users.
103 return;
104
105 std::sort(List.begin(), List.end(),
106 [&OM, ID](const Entry &L, const Entry &R) {
107 const Use *LU = L.first;
108 const Use *RU = R.first;
109 auto LID = OM.lookup(LU->getUser()).first;
110 auto RID = OM.lookup(RU->getUser()).first;
111 // If ID is 4, then expect: 7 6 5 1 2 3.
112 if (LID < RID) {
113 if (RID < ID)
114 return true;
115 return false;
116 }
117 if (RID < LID) {
118 if (LID < ID)
119 return false;
120 return true;
121 }
122 // LID and RID are equal, so we have different operands of the same user.
123 // Assume operands are added in order for all instructions.
124 if (LU->getOperandNo() < RU->getOperandNo())
125 return LID < ID;
126 return ID < LID;
127 });
128
129 if (std::is_sorted(
130 List.begin(), List.end(),
131 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
132 // Order is already correct.
133 return;
134
135 // Store the shuffle.
Duncan P. N. Exon Smithf849ace2014-07-28 22:41:50 +0000136 UseListOrder O(V, F, List.size());
137 assert(List.size() == O.Shuffle.size() && "Wrong size");
138 for (size_t I = 0, E = List.size(); I != E; ++I)
139 O.Shuffle[I] = List[I].second;
140 Stack.emplace_back(std::move(O));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000141}
142
143static void predictValueUseListOrder(const Value *V, const Function *F,
144 OrderMap &OM, UseListOrderStack &Stack) {
145 auto &IDPair = OM[V];
146 assert(IDPair.first && "Unmapped value");
147 if (IDPair.second)
148 // Already predicted.
149 return;
150
151 // Do the actual prediction.
152 IDPair.second = true;
153 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
154 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
155
156 // Recursive descent into constants.
157 if (const Constant *C = dyn_cast<Constant>(V))
158 if (C->getNumOperands() && !isa<GlobalValue>(C))
159 for (const Value *Op : C->operands())
160 if (isa<Constant>(Op) && !isa<GlobalValue>(Op))
161 predictValueUseListOrder(Op, F, OM, Stack);
162}
163
164static UseListOrderStack predictUseListOrder(const Module *M) {
165 OrderMap OM = orderModule(M);
166
167 // Use-list orders need to be serialized after all the users have been added
168 // to a value, or else the shuffles will be incomplete. Store them per
169 // function in a stack.
170 //
171 // Aside from function order, the order of values doesn't matter much here.
172 UseListOrderStack Stack;
173
174 // We want to visit the functions backward now so we can list function-local
175 // constants in the last Function they're used in. Module-level constants
176 // have already been visited above.
177 for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
178 const Function &F = *I;
179 if (F.isDeclaration())
180 continue;
181 for (const BasicBlock &BB : F)
182 predictValueUseListOrder(&BB, &F, OM, Stack);
183 for (const Argument &A : F.args())
184 predictValueUseListOrder(&A, &F, OM, Stack);
185 for (const BasicBlock &BB : F)
186 for (const Instruction &I : BB)
187 for (const Value *Op : I.operands())
188 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
189 isa<InlineAsm>(*Op))
190 predictValueUseListOrder(Op, &F, OM, Stack);
191 for (const BasicBlock &BB : F)
192 for (const Instruction &I : BB)
193 predictValueUseListOrder(&I, &F, OM, Stack);
194 }
195
196 // Visit globals last, since the module-level use-list block will be seen
197 // before the function bodies are processed.
198 for (const GlobalVariable &G : M->globals())
199 predictValueUseListOrder(&G, nullptr, OM, Stack);
200 for (const Function &F : *M)
201 predictValueUseListOrder(&F, nullptr, OM, Stack);
202 for (const GlobalAlias &A : M->aliases())
203 predictValueUseListOrder(&A, nullptr, OM, Stack);
204 for (const GlobalVariable &G : M->globals())
205 if (G.hasInitializer())
206 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
207 for (const GlobalAlias &A : M->aliases())
208 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
209 for (const Function &F : *M)
210 if (F.hasPrefixData())
211 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
212
213 return Stack;
214}
215
Duncan Sandse6beec62012-11-13 12:59:33 +0000216static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
217 return V.first->getType()->isIntOrIntVectorTy();
Chris Lattner430e80d2007-05-04 05:21:47 +0000218}
219
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000220/// ValueEnumerator - Enumerate module-level information.
221ValueEnumerator::ValueEnumerator(const Module *M) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000222 if (shouldPreserveBitcodeUseListOrder())
223 UseListOrders = predictUseListOrder(M);
224
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000225 // Enumerate the global variables.
226 for (Module::const_global_iterator I = M->global_begin(),
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000227
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000228 E = M->global_end(); I != E; ++I)
229 EnumerateValue(I);
230
231 // Enumerate the functions.
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000232 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000233 EnumerateValue(I);
Devang Patel4c758ea2008-09-25 21:00:45 +0000234 EnumerateAttributes(cast<Function>(I)->getAttributes());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000235 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000236
Chris Lattner44c17072007-04-26 02:46:40 +0000237 // Enumerate the aliases.
238 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
239 I != E; ++I)
240 EnumerateValue(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000241
Chris Lattner430e80d2007-05-04 05:21:47 +0000242 // Remember what is the cutoff between globalvalue's and other constants.
243 unsigned FirstConstant = Values.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000244
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000245 // Enumerate the global variable initializers.
246 for (Module::const_global_iterator I = M->global_begin(),
247 E = M->global_end(); I != E; ++I)
248 if (I->hasInitializer())
249 EnumerateValue(I->getInitializer());
250
Chris Lattner44c17072007-04-26 02:46:40 +0000251 // Enumerate the aliasees.
252 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
253 I != E; ++I)
254 EnumerateValue(I->getAliasee());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000255
Peter Collingbourne3fa50f92013-09-16 01:08:15 +0000256 // Enumerate the prefix data constants.
257 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
258 if (I->hasPrefixData())
259 EnumerateValue(I->getPrefixData());
260
Joe Abbeybc6f4ba2013-04-01 02:28:07 +0000261 // Insert constants and metadata that are named at module level into the slot
Devang Patelfcfee0f2010-01-07 19:39:36 +0000262 // pool so that the module symbol table can refer to them...
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000263 EnumerateValueSymbolTable(M->getValueSymbolTable());
Dan Gohman2637cc12010-07-21 23:38:33 +0000264 EnumerateNamedMetadata(M);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000265
Chris Lattner8dace892009-12-31 00:51:46 +0000266 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
267
Chris Lattner5f640b92007-04-26 03:50:57 +0000268 // Enumerate types used by function bodies and argument lists.
Rafael Espindola087d6272014-06-17 03:00:40 +0000269 for (const Function &F : *M) {
270 for (const Argument &A : F.args())
271 EnumerateType(A.getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000272
Rafael Espindola087d6272014-06-17 03:00:40 +0000273 for (const BasicBlock &BB : F)
274 for (const Instruction &I : BB) {
275 for (const Use &Op : I.operands()) {
276 if (MDNode *MD = dyn_cast<MDNode>(&Op))
Victor Hernandez1b081382010-02-06 01:21:09 +0000277 if (MD->isFunctionLocal() && MD->getFunction())
Victor Hernandez572218b2010-01-14 19:54:11 +0000278 // These will get enumerated during function-incorporation.
279 continue;
Rafael Espindola087d6272014-06-17 03:00:40 +0000280 EnumerateOperandType(Op);
Victor Hernandez572218b2010-01-14 19:54:11 +0000281 }
Rafael Espindola087d6272014-06-17 03:00:40 +0000282 EnumerateType(I.getType());
283 if (const CallInst *CI = dyn_cast<CallInst>(&I))
Devang Patel4c758ea2008-09-25 21:00:45 +0000284 EnumerateAttributes(CI->getAttributes());
Rafael Espindola087d6272014-06-17 03:00:40 +0000285 else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
Devang Patel4c758ea2008-09-25 21:00:45 +0000286 EnumerateAttributes(II->getAttributes());
Devang Patelaf206b82009-09-18 19:26:43 +0000287
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000288 // Enumerate metadata attached with this instruction.
Devang Patel6da5dbf2009-10-22 18:55:16 +0000289 MDs.clear();
Rafael Espindola087d6272014-06-17 03:00:40 +0000290 I.getAllMetadataOtherThanDebugLoc(MDs);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000291 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
Victor Hernandez572218b2010-01-14 19:54:11 +0000292 EnumerateMetadata(MDs[i].second);
Joe Abbey2ad8df22012-11-25 15:23:39 +0000293
Rafael Espindola087d6272014-06-17 03:00:40 +0000294 if (!I.getDebugLoc().isUnknown()) {
Chris Lattner07d09ed2010-04-03 02:17:50 +0000295 MDNode *Scope, *IA;
Rafael Espindola087d6272014-06-17 03:00:40 +0000296 I.getDebugLoc().getScopeAndInlinedAt(Scope, IA, I.getContext());
Chris Lattner07d09ed2010-04-03 02:17:50 +0000297 if (Scope) EnumerateMetadata(Scope);
298 if (IA) EnumerateMetadata(IA);
299 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000300 }
301 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000302
Chris Lattner430e80d2007-05-04 05:21:47 +0000303 // Optimize constant ordering.
304 OptimizeConstants(FirstConstant, Values.size());
Rafael Espindola337a1b22011-04-06 16:49:37 +0000305}
306
Devang Patelaf206b82009-09-18 19:26:43 +0000307unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
308 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000309 assert(I != InstructionMap.end() && "Instruction is not mapped!");
Dan Gohman1f4b0282010-08-25 17:09:50 +0000310 return I->second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000311}
Devang Patelaf206b82009-09-18 19:26:43 +0000312
David Majnemerdad0a642014-06-27 18:19:56 +0000313unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
314 unsigned ComdatID = Comdats.idFor(C);
315 assert(ComdatID && "Comdat not found!");
316 return ComdatID;
317}
318
Devang Patelaf206b82009-09-18 19:26:43 +0000319void ValueEnumerator::setInstructionID(const Instruction *I) {
320 InstructionMap[I] = InstructionCount++;
321}
322
Devang Patel05eb6172009-08-04 06:00:18 +0000323unsigned ValueEnumerator::getValueID(const Value *V) const {
Devang Patelac277eb2010-01-22 22:52:10 +0000324 if (isa<MDNode>(V) || isa<MDString>(V)) {
Devang Patel05eb6172009-08-04 06:00:18 +0000325 ValueMapType::const_iterator I = MDValueMap.find(V);
326 assert(I != MDValueMap.end() && "Value not in slotcalculator!");
327 return I->second-1;
328 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000329
Devang Patel05eb6172009-08-04 06:00:18 +0000330 ValueMapType::const_iterator I = ValueMap.find(V);
331 assert(I != ValueMap.end() && "Value not in slotcalculator!");
332 return I->second-1;
333}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000334
Chad Rosier78037a92011-12-07 20:44:46 +0000335void ValueEnumerator::dump() const {
336 print(dbgs(), ValueMap, "Default");
337 dbgs() << '\n';
338 print(dbgs(), MDValueMap, "MetaData");
339 dbgs() << '\n';
340}
341
342void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
343 const char *Name) const {
344
345 OS << "Map Name: " << Name << "\n";
346 OS << "Size: " << Map.size() << "\n";
347 for (ValueMapType::const_iterator I = Map.begin(),
348 E = Map.end(); I != E; ++I) {
349
350 const Value *V = I->first;
351 if (V->hasName())
352 OS << "Value: " << V->getName();
353 else
354 OS << "Value: [null]\n";
355 V->dump();
356
357 OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
Chandler Carruthcdf47882014-03-09 03:16:01 +0000358 for (const Use &U : V->uses()) {
359 if (&U != &*V->use_begin())
Chad Rosier78037a92011-12-07 20:44:46 +0000360 OS << ",";
Chandler Carruthcdf47882014-03-09 03:16:01 +0000361 if(U->hasName())
362 OS << " " << U->getName();
Chad Rosier78037a92011-12-07 20:44:46 +0000363 else
364 OS << " [null]";
365
366 }
367 OS << "\n\n";
368 }
369}
370
Chris Lattner430e80d2007-05-04 05:21:47 +0000371/// OptimizeConstants - Reorder constant pool for denser encoding.
372void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
373 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000374
Duncan P. N. Exon Smith15eb0ab2014-07-25 16:13:16 +0000375 if (shouldPreserveBitcodeUseListOrder())
376 // Optimizing constants makes the use-list order difficult to predict.
377 // Disable it for now when trying to preserve the order.
378 return;
379
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000380 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
381 [this](const std::pair<const Value *, unsigned> &LHS,
382 const std::pair<const Value *, unsigned> &RHS) {
383 // Sort by plane.
384 if (LHS.first->getType() != RHS.first->getType())
385 return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
386 // Then by frequency.
387 return LHS.second > RHS.second;
388 });
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000389
Duncan Sandse6beec62012-11-13 12:59:33 +0000390 // Ensure that integer and vector of integer constants are at the start of the
391 // constant pool. This is important so that GEP structure indices come before
392 // gep constant exprs.
Chris Lattner430e80d2007-05-04 05:21:47 +0000393 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
Duncan Sandse6beec62012-11-13 12:59:33 +0000394 isIntOrIntVectorValue);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000395
Chris Lattner430e80d2007-05-04 05:21:47 +0000396 // Rebuild the modified portion of ValueMap.
397 for (; CstStart != CstEnd; ++CstStart)
398 ValueMap[Values[CstStart].first] = CstStart+1;
399}
400
401
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000402/// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
403/// table into the values table.
404void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000405 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000406 VI != VE; ++VI)
407 EnumerateValue(VI->getValue());
408}
409
Dan Gohman2637cc12010-07-21 23:38:33 +0000410/// EnumerateNamedMetadata - Insert all of the values referenced by
411/// named metadata in the specified module.
412void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
413 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
414 E = M->named_metadata_end(); I != E; ++I)
415 EnumerateNamedMDNode(I);
Devang Patelfcfee0f2010-01-07 19:39:36 +0000416}
417
Devang Patel99ff5a82010-01-09 00:30:14 +0000418void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
Devang Patel99ff5a82010-01-09 00:30:14 +0000419 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
Dan Gohmand3d2bbe2010-08-24 02:01:24 +0000420 EnumerateMetadata(MD->getOperand(i));
Devang Patel99ff5a82010-01-09 00:30:14 +0000421}
422
Dan Gohmanc828c542010-08-24 02:24:03 +0000423/// EnumerateMDNodeOperands - Enumerate all non-function-local values
424/// and types referenced by the given MDNode.
425void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
426 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
427 if (Value *V = N->getOperand(i)) {
428 if (isa<MDNode>(V) || isa<MDString>(V))
429 EnumerateMetadata(V);
430 else if (!isa<Instruction>(V) && !isa<Argument>(V))
431 EnumerateValue(V);
432 } else
433 EnumerateType(Type::getVoidTy(N->getContext()));
434 }
435}
436
Devang Patelac277eb2010-01-22 22:52:10 +0000437void ValueEnumerator::EnumerateMetadata(const Value *MD) {
Benjamin Kramer14bb1142010-01-23 09:54:23 +0000438 assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
Dan Gohmanc828c542010-08-24 02:24:03 +0000439
440 // Enumerate the type of this value.
441 EnumerateType(MD->getType());
442
443 const MDNode *N = dyn_cast<MDNode>(MD);
444
445 // In the module-level pass, skip function-local nodes themselves, but
446 // do walk their operands.
447 if (N && N->isFunctionLocal() && N->getFunction()) {
448 EnumerateMDNodeOperands(N);
449 return;
450 }
451
Devang Patel05eb6172009-08-04 06:00:18 +0000452 // Check to see if it's already in!
453 unsigned &MDValueID = MDValueMap[MD];
454 if (MDValueID) {
455 // Increment use count.
456 MDValues[MDValueID-1].second++;
457 return;
458 }
Devang Patel05eb6172009-08-04 06:00:18 +0000459 MDValues.push_back(std::make_pair(MD, 1U));
460 MDValueID = MDValues.size();
Dan Gohmanc828c542010-08-24 02:24:03 +0000461
462 // Enumerate all non-function-local operands.
463 if (N)
464 EnumerateMDNodeOperands(N);
465}
466
467/// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
468/// information reachable from the given MDNode.
469void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
470 assert(N->isFunctionLocal() && N->getFunction() &&
471 "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
472
473 // Enumerate the type of this value.
474 EnumerateType(N->getType());
475
476 // Check to see if it's already in!
477 unsigned &MDValueID = MDValueMap[N];
478 if (MDValueID) {
479 // Increment use count.
480 MDValues[MDValueID-1].second++;
481 return;
482 }
483 MDValues.push_back(std::make_pair(N, 1U));
484 MDValueID = MDValues.size();
485
486 // To incoroporate function-local information visit all function-local
487 // MDNodes and all function-local values they reference.
488 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
489 if (Value *V = N->getOperand(i)) {
Dan Gohman10215a12010-08-24 02:40:27 +0000490 if (MDNode *O = dyn_cast<MDNode>(V)) {
Dan Gohmanc828c542010-08-24 02:24:03 +0000491 if (O->isFunctionLocal() && O->getFunction())
492 EnumerateFunctionLocalMetadata(O);
Dan Gohman10215a12010-08-24 02:40:27 +0000493 } else if (isa<Instruction>(V) || isa<Argument>(V))
Dan Gohmanc828c542010-08-24 02:24:03 +0000494 EnumerateValue(V);
495 }
496
497 // Also, collect all function-local MDNodes for easy access.
498 FunctionLocalMDs.push_back(N);
Devang Patel05eb6172009-08-04 06:00:18 +0000499}
500
Victor Hernandez572218b2010-01-14 19:54:11 +0000501void ValueEnumerator::EnumerateValue(const Value *V) {
Chris Lattner8dace892009-12-31 00:51:46 +0000502 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
Dan Gohmanc828c542010-08-24 02:24:03 +0000503 assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
504 "EnumerateValue doesn't handle Metadata!");
Devang Patel05eb6172009-08-04 06:00:18 +0000505
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000506 // Check to see if it's already in!
507 unsigned &ValueID = ValueMap[V];
508 if (ValueID) {
509 // Increment use count.
510 Values[ValueID-1].second++;
511 return;
512 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000513
David Majnemerdad0a642014-06-27 18:19:56 +0000514 if (auto *GO = dyn_cast<GlobalObject>(V))
515 if (const Comdat *C = GO->getComdat())
516 Comdats.insert(C);
517
Chris Lattner9ee48362007-05-06 01:00:28 +0000518 // Enumerate the type of this value.
519 EnumerateType(V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000520
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000521 if (const Constant *C = dyn_cast<Constant>(V)) {
522 if (isa<GlobalValue>(C)) {
523 // Initializers for globals are handled explicitly elsewhere.
Chris Lattner9ee48362007-05-06 01:00:28 +0000524 } else if (C->getNumOperands()) {
525 // If a constant has operands, enumerate them. This makes sure that if a
526 // constant has uses (for example an array of const ints), that they are
527 // inserted also.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000528
Chris Lattner9ee48362007-05-06 01:00:28 +0000529 // We prefer to enumerate them with values before we enumerate the user
530 // itself. This makes it more likely that we can avoid forward references
531 // in the reader. We know that there can be no cycles in the constants
532 // graph that don't go through a global variable.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000533 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
534 I != E; ++I)
Chris Lattneraa99c942009-11-01 01:27:45 +0000535 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
Victor Hernandez572218b2010-01-14 19:54:11 +0000536 EnumerateValue(*I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000537
Chris Lattner9ee48362007-05-06 01:00:28 +0000538 // Finally, add the value. Doing this could make the ValueID reference be
539 // dangling, don't reuse it.
540 Values.push_back(std::make_pair(V, 1U));
541 ValueMap[V] = Values.size();
542 return;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000543 }
544 }
Devang Patele059ba6e2009-07-23 01:07:34 +0000545
Chris Lattner9ee48362007-05-06 01:00:28 +0000546 // Add the value.
547 Values.push_back(std::make_pair(V, 1U));
548 ValueID = Values.size();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000549}
550
551
Chris Lattner229907c2011-07-18 04:54:35 +0000552void ValueEnumerator::EnumerateType(Type *Ty) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000553 unsigned *TypeID = &TypeMap[Ty];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000554
Rafael Espindola337a1b22011-04-06 16:49:37 +0000555 // We've already seen this type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000556 if (*TypeID)
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000557 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000558
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000559 // If it is a non-anonymous struct, mark the type as being visited so that we
560 // don't recursively visit it. This is safe because we allow forward
561 // references of these in the bitcode reader.
Chris Lattner229907c2011-07-18 04:54:35 +0000562 if (StructType *STy = dyn_cast<StructType>(Ty))
Chris Lattner335d3992011-08-12 18:06:37 +0000563 if (!STy->isLiteral())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000564 *TypeID = ~0U;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000565
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000566 // Enumerate all of the subtypes before we enumerate this type. This ensures
567 // that the type will be enumerated in an order that can be directly built.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000568 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
569 I != E; ++I)
570 EnumerateType(*I);
Joe Abbey2ad8df22012-11-25 15:23:39 +0000571
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000572 // Refresh the TypeID pointer in case the table rehashed.
573 TypeID = &TypeMap[Ty];
Joe Abbey2ad8df22012-11-25 15:23:39 +0000574
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000575 // Check to see if we got the pointer another way. This can happen when
576 // enumerating recursive types that hit the base case deeper than they start.
577 //
578 // If this is actually a struct that we are treating as forward ref'able,
579 // then emit the definition now that all of its contents are available.
580 if (*TypeID && *TypeID != ~0U)
581 return;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000582
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000583 // Add this type now that its contents are all happily enumerated.
584 Types.push_back(Ty);
Joe Abbey2ad8df22012-11-25 15:23:39 +0000585
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000586 *TypeID = Types.size();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000587}
588
Chris Lattner76fd90f2007-05-06 08:35:19 +0000589// Enumerate the types for the specified value. If the value is a constant,
590// walk through it, enumerating the types of the constant.
Victor Hernandez572218b2010-01-14 19:54:11 +0000591void ValueEnumerator::EnumerateOperandType(const Value *V) {
Chris Lattner76fd90f2007-05-06 08:35:19 +0000592 EnumerateType(V->getType());
Joe Abbey2ad8df22012-11-25 15:23:39 +0000593
Chris Lattner76fd90f2007-05-06 08:35:19 +0000594 if (const Constant *C = dyn_cast<Constant>(V)) {
595 // If this constant is already enumerated, ignore it, we know its type must
596 // be enumerated.
597 if (ValueMap.count(V)) return;
598
599 // This constant may have operands, make sure to enumerate the types in
600 // them.
Chris Lattnerf540d742009-10-28 05:24:40 +0000601 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
Jay Foad0159a1e2011-04-11 09:48:55 +0000602 const Value *Op = C->getOperand(i);
Joe Abbey2ad8df22012-11-25 15:23:39 +0000603
Chris Lattnerf540d742009-10-28 05:24:40 +0000604 // Don't enumerate basic blocks here, this happens as operands to
605 // blockaddress.
606 if (isa<BasicBlock>(Op)) continue;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000607
Dan Gohman9cfe5322010-08-25 17:09:03 +0000608 EnumerateOperandType(Op);
Chris Lattnerf540d742009-10-28 05:24:40 +0000609 }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000610
611 if (const MDNode *N = dyn_cast<MDNode>(V)) {
Chris Lattner9b493022009-12-31 01:22:29 +0000612 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
613 if (Value *Elem = N->getOperand(i))
Victor Hernandez572218b2010-01-14 19:54:11 +0000614 EnumerateOperandType(Elem);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000615 }
Devang Patele059ba6e2009-07-23 01:07:34 +0000616 } else if (isa<MDString>(V) || isa<MDNode>(V))
Dan Gohmanab09a122010-08-24 02:10:52 +0000617 EnumerateMetadata(V);
Chris Lattner76fd90f2007-05-06 08:35:19 +0000618}
619
Bill Wendling7b5f4f32013-02-12 08:01:22 +0000620void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
Chris Lattner8a923e72008-03-12 17:45:29 +0000621 if (PAL.isEmpty()) return; // null is always 0.
Bill Wendling7b5f4f32013-02-12 08:01:22 +0000622
Chris Lattnere4bbad62007-05-03 22:46:43 +0000623 // Do a lookup.
Bill Wendling7b5f4f32013-02-12 08:01:22 +0000624 unsigned &Entry = AttributeMap[PAL];
Chris Lattnere4bbad62007-05-03 22:46:43 +0000625 if (Entry == 0) {
626 // Never saw this before, add it.
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000627 Attribute.push_back(PAL);
628 Entry = Attribute.size();
Chris Lattnere4bbad62007-05-03 22:46:43 +0000629 }
Bill Wendling51f612e2013-02-10 23:06:02 +0000630
631 // Do lookups for all attribute groups.
632 for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
633 AttributeSet AS = PAL.getSlotAttributes(i);
Bill Wendling92ed7002013-02-11 22:33:26 +0000634 unsigned &Entry = AttributeGroupMap[AS];
Bill Wendling51f612e2013-02-10 23:06:02 +0000635 if (Entry == 0) {
Bill Wendling92ed7002013-02-11 22:33:26 +0000636 AttributeGroups.push_back(AS);
637 Entry = AttributeGroups.size();
Bill Wendling51f612e2013-02-10 23:06:02 +0000638 }
639 }
Chris Lattnere4bbad62007-05-03 22:46:43 +0000640}
641
Chad Rosier6a11b642011-06-03 17:02:19 +0000642void ValueEnumerator::incorporateFunction(const Function &F) {
Nick Lewyckya72e1af2010-02-25 08:30:17 +0000643 InstructionCount = 0;
Chris Lattnere6e364c2007-04-26 05:53:54 +0000644 NumModuleValues = Values.size();
Dan Gohmanc828c542010-08-24 02:24:03 +0000645 NumModuleMDValues = MDValues.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000646
Chris Lattner5f640b92007-04-26 03:50:57 +0000647 // Adding function arguments to the value table.
Dan Gohman9a54c172010-07-16 22:58:39 +0000648 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
649 I != E; ++I)
Chris Lattner5f640b92007-04-26 03:50:57 +0000650 EnumerateValue(I);
651
Chris Lattnere6e364c2007-04-26 05:53:54 +0000652 FirstFuncConstantID = Values.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000653
Chris Lattner5f640b92007-04-26 03:50:57 +0000654 // Add all function-level constants to the value table.
655 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
656 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000657 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
Chris Lattner5f640b92007-04-26 03:50:57 +0000658 OI != E; ++OI) {
659 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
660 isa<InlineAsm>(*OI))
661 EnumerateValue(*OI);
662 }
Chris Lattner7c37b012007-04-26 04:42:16 +0000663 BasicBlocks.push_back(BB);
Chris Lattner6be58c62007-05-03 22:18:21 +0000664 ValueMap[BB] = BasicBlocks.size();
Chris Lattner5f640b92007-04-26 03:50:57 +0000665 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000666
Chris Lattner430e80d2007-05-04 05:21:47 +0000667 // Optimize the constant layout.
668 OptimizeConstants(FirstFuncConstantID, Values.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000669
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000670 // Add the function's parameter attributes so they are available for use in
671 // the function's instruction.
Devang Patel4c758ea2008-09-25 21:00:45 +0000672 EnumerateAttributes(F.getAttributes());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000673
Chris Lattnere6e364c2007-04-26 05:53:54 +0000674 FirstInstID = Values.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000675
Devang Pateldf84e8b2010-06-02 23:05:04 +0000676 SmallVector<MDNode *, 8> FnLocalMDVector;
Chris Lattner5f640b92007-04-26 03:50:57 +0000677 // Add all of the instructions.
678 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000679 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
Victor Hernandezcad73282010-01-13 19:36:16 +0000680 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
681 OI != E; ++OI) {
Victor Hernandez572218b2010-01-14 19:54:11 +0000682 if (MDNode *MD = dyn_cast<MDNode>(*OI))
Victor Hernandez1b081382010-02-06 01:21:09 +0000683 if (MD->isFunctionLocal() && MD->getFunction())
Victor Hernandezd44ee352010-02-04 01:13:08 +0000684 // Enumerate metadata after the instructions they might refer to.
Devang Pateldf84e8b2010-06-02 23:05:04 +0000685 FnLocalMDVector.push_back(MD);
Victor Hernandezcad73282010-01-13 19:36:16 +0000686 }
Dan Gohmanc828c542010-08-24 02:24:03 +0000687
688 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
689 I->getAllMetadataOtherThanDebugLoc(MDs);
690 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
691 MDNode *N = MDs[i].second;
692 if (N->isFunctionLocal() && N->getFunction())
693 FnLocalMDVector.push_back(N);
694 }
Joe Abbey2ad8df22012-11-25 15:23:39 +0000695
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000696 if (!I->getType()->isVoidTy())
Chris Lattner5f640b92007-04-26 03:50:57 +0000697 EnumerateValue(I);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000698 }
699 }
Victor Hernandezd44ee352010-02-04 01:13:08 +0000700
701 // Add all of the function-local metadata.
Devang Pateldf84e8b2010-06-02 23:05:04 +0000702 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
Dan Gohmanc828c542010-08-24 02:24:03 +0000703 EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000704}
705
Chad Rosier6a11b642011-06-03 17:02:19 +0000706void ValueEnumerator::purgeFunction() {
Chris Lattner5f640b92007-04-26 03:50:57 +0000707 /// Remove purged values from the ValueMap.
Chris Lattnere6e364c2007-04-26 05:53:54 +0000708 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
Chris Lattner5f640b92007-04-26 03:50:57 +0000709 ValueMap.erase(Values[i].first);
Dan Gohmanc828c542010-08-24 02:24:03 +0000710 for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
711 MDValueMap.erase(MDValues[i].first);
Chris Lattner7c37b012007-04-26 04:42:16 +0000712 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
713 ValueMap.erase(BasicBlocks[i]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000714
Chris Lattnere6e364c2007-04-26 05:53:54 +0000715 Values.resize(NumModuleValues);
Dan Gohmanc828c542010-08-24 02:24:03 +0000716 MDValues.resize(NumModuleMDValues);
Chris Lattner7c37b012007-04-26 04:42:16 +0000717 BasicBlocks.clear();
Dan Gohman22161da2010-08-25 17:11:16 +0000718 FunctionLocalMDs.clear();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000719}
Chris Lattnerf540d742009-10-28 05:24:40 +0000720
721static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
722 DenseMap<const BasicBlock*, unsigned> &IDMap) {
723 unsigned Counter = 0;
724 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
725 IDMap[BB] = ++Counter;
726}
727
728/// getGlobalBasicBlockID - This returns the function-specific ID for the
729/// specified basic block. This is relatively expensive information, so it
730/// should only be used by rare constructs such as address-of-label.
731unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
732 unsigned &Idx = GlobalBasicBlockIDs[BB];
733 if (Idx != 0)
Chris Lattneraa99c942009-11-01 01:27:45 +0000734 return Idx-1;
Chris Lattnerf540d742009-10-28 05:24:40 +0000735
736 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
737 return getGlobalBasicBlockID(BB);
738}
739