ValueEnumerator.cpp revision d711dec946b6408791ca59eb98e363ef04bbd4aa
1//===-- ValueEnumerator.cpp - Number values and types for bitcode writer --===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ValueEnumerator class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ValueEnumerator.h"
15#include "llvm/ADT/SmallPtrSet.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
20#include "llvm/ValueSymbolTable.h"
21#include "llvm/Instructions.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/Support/raw_ostream.h"
24#include <algorithm>
25using namespace llvm;
26
27namespace llvm_3_2 {
28
29static bool isIntegerValue(const std::pair<const Value*, unsigned> &V) {
30  return V.first->getType()->isIntegerTy();
31}
32
33/// ValueEnumerator - Enumerate module-level information.
34ValueEnumerator::ValueEnumerator(const Module *M) {
35  // Enumerate the global variables.
36  for (Module::const_global_iterator I = M->global_begin(),
37         E = M->global_end(); I != E; ++I)
38    EnumerateValue(I);
39
40  // Enumerate the functions.
41  for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
42    EnumerateValue(I);
43    EnumerateAttributes(cast<Function>(I)->getAttributes());
44  }
45
46  // Enumerate the aliases.
47  for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
48       I != E; ++I)
49    EnumerateValue(I);
50
51  // Remember what is the cutoff between globalvalue's and other constants.
52  unsigned FirstConstant = Values.size();
53
54  // Enumerate the global variable initializers.
55  for (Module::const_global_iterator I = M->global_begin(),
56         E = M->global_end(); I != E; ++I)
57    if (I->hasInitializer())
58      EnumerateValue(I->getInitializer());
59
60  // Enumerate the aliasees.
61  for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
62       I != E; ++I)
63    EnumerateValue(I->getAliasee());
64
65  // Insert constants and metadata that are named at module level into the slot
66  // pool so that the module symbol table can refer to them...
67  EnumerateValueSymbolTable(M->getValueSymbolTable());
68  EnumerateNamedMetadata(M);
69
70  SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
71
72  // Enumerate types used by function bodies and argument lists.
73  for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
74
75    for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
76         I != E; ++I)
77      EnumerateType(I->getType());
78
79    for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
80      for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
81        for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
82             OI != E; ++OI) {
83          if (MDNode *MD = dyn_cast<MDNode>(*OI))
84            if (MD->isFunctionLocal() && MD->getFunction())
85              // These will get enumerated during function-incorporation.
86              continue;
87          EnumerateOperandType(*OI);
88        }
89        EnumerateType(I->getType());
90        if (const CallInst *CI = dyn_cast<CallInst>(I))
91          EnumerateAttributes(CI->getAttributes());
92        else if (const InvokeInst *II = dyn_cast<InvokeInst>(I))
93          EnumerateAttributes(II->getAttributes());
94
95        // Enumerate metadata attached with this instruction.
96        MDs.clear();
97        I->getAllMetadataOtherThanDebugLoc(MDs);
98        for (unsigned i = 0, e = MDs.size(); i != e; ++i)
99          EnumerateMetadata(MDs[i].second);
100
101        if (!I->getDebugLoc().isUnknown()) {
102          MDNode *Scope, *IA;
103          I->getDebugLoc().getScopeAndInlinedAt(Scope, IA, I->getContext());
104          if (Scope) EnumerateMetadata(Scope);
105          if (IA) EnumerateMetadata(IA);
106        }
107      }
108  }
109
110  // Optimize constant ordering.
111  OptimizeConstants(FirstConstant, Values.size());
112}
113
114unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
115  InstructionMapType::const_iterator I = InstructionMap.find(Inst);
116  assert(I != InstructionMap.end() && "Instruction is not mapped!");
117  return I->second;
118}
119
120void ValueEnumerator::setInstructionID(const Instruction *I) {
121  InstructionMap[I] = InstructionCount++;
122}
123
124unsigned ValueEnumerator::getValueID(const Value *V) const {
125  if (isa<MDNode>(V) || isa<MDString>(V)) {
126    ValueMapType::const_iterator I = MDValueMap.find(V);
127    assert(I != MDValueMap.end() && "Value not in slotcalculator!");
128    return I->second-1;
129  }
130
131  ValueMapType::const_iterator I = ValueMap.find(V);
132  assert(I != ValueMap.end() && "Value not in slotcalculator!");
133  return I->second-1;
134}
135
136void ValueEnumerator::dump() const {
137  print(dbgs(), ValueMap, "Default");
138  dbgs() << '\n';
139  print(dbgs(), MDValueMap, "MetaData");
140  dbgs() << '\n';
141}
142
143void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
144                            const char *Name) const {
145
146  OS << "Map Name: " << Name << "\n";
147  OS << "Size: " << Map.size() << "\n";
148  for (ValueMapType::const_iterator I = Map.begin(),
149         E = Map.end(); I != E; ++I) {
150
151    const Value *V = I->first;
152    if (V->hasName())
153      OS << "Value: " << V->getName();
154    else
155      OS << "Value: [null]\n";
156    V->dump();
157
158    OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
159    for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
160         UI != UE; ++UI) {
161      if (UI != V->use_begin())
162        OS << ",";
163      if((*UI)->hasName())
164        OS << " " << (*UI)->getName();
165      else
166        OS << " [null]";
167
168    }
169    OS <<  "\n\n";
170  }
171}
172
173// Optimize constant ordering.
174namespace {
175  struct CstSortPredicate {
176    ValueEnumerator &VE;
177    explicit CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
178    bool operator()(const std::pair<const Value*, unsigned> &LHS,
179                    const std::pair<const Value*, unsigned> &RHS) {
180      // Sort by plane.
181      if (LHS.first->getType() != RHS.first->getType())
182        return VE.getTypeID(LHS.first->getType()) <
183               VE.getTypeID(RHS.first->getType());
184      // Then by frequency.
185      return LHS.second > RHS.second;
186    }
187  };
188}
189
190/// OptimizeConstants - Reorder constant pool for denser encoding.
191void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
192  if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
193
194  CstSortPredicate P(*this);
195  std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
196
197  // Ensure that integer constants are at the start of the constant pool.  This
198  // is important so that GEP structure indices come before gep constant exprs.
199  std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
200                 isIntegerValue);
201
202  // Rebuild the modified portion of ValueMap.
203  for (; CstStart != CstEnd; ++CstStart)
204    ValueMap[Values[CstStart].first] = CstStart+1;
205}
206
207
208/// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
209/// table into the values table.
210void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
211  for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
212       VI != VE; ++VI)
213    EnumerateValue(VI->getValue());
214}
215
216/// EnumerateNamedMetadata - Insert all of the values referenced by
217/// named metadata in the specified module.
218void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
219  for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
220       E = M->named_metadata_end(); I != E; ++I)
221    EnumerateNamedMDNode(I);
222}
223
224void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
225  for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
226    EnumerateMetadata(MD->getOperand(i));
227}
228
229/// EnumerateMDNodeOperands - Enumerate all non-function-local values
230/// and types referenced by the given MDNode.
231void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
232  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
233    if (Value *V = N->getOperand(i)) {
234      if (isa<MDNode>(V) || isa<MDString>(V))
235        EnumerateMetadata(V);
236      else if (!isa<Instruction>(V) && !isa<Argument>(V))
237        EnumerateValue(V);
238    } else
239      EnumerateType(Type::getVoidTy(N->getContext()));
240  }
241}
242
243void ValueEnumerator::EnumerateMetadata(const Value *MD) {
244  assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
245
246  // Enumerate the type of this value.
247  EnumerateType(MD->getType());
248
249  const MDNode *N = dyn_cast<MDNode>(MD);
250
251  // In the module-level pass, skip function-local nodes themselves, but
252  // do walk their operands.
253  if (N && N->isFunctionLocal() && N->getFunction()) {
254    EnumerateMDNodeOperands(N);
255    return;
256  }
257
258  // Check to see if it's already in!
259  unsigned &MDValueID = MDValueMap[MD];
260  if (MDValueID) {
261    // Increment use count.
262    MDValues[MDValueID-1].second++;
263    return;
264  }
265  MDValues.push_back(std::make_pair(MD, 1U));
266  MDValueID = MDValues.size();
267
268  // Enumerate all non-function-local operands.
269  if (N)
270    EnumerateMDNodeOperands(N);
271}
272
273/// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
274/// information reachable from the given MDNode.
275void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
276  assert(N->isFunctionLocal() && N->getFunction() &&
277         "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
278
279  // Enumerate the type of this value.
280  EnumerateType(N->getType());
281
282  // Check to see if it's already in!
283  unsigned &MDValueID = MDValueMap[N];
284  if (MDValueID) {
285    // Increment use count.
286    MDValues[MDValueID-1].second++;
287    return;
288  }
289  MDValues.push_back(std::make_pair(N, 1U));
290  MDValueID = MDValues.size();
291
292  // To incoroporate function-local information visit all function-local
293  // MDNodes and all function-local values they reference.
294  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
295    if (Value *V = N->getOperand(i)) {
296      if (MDNode *O = dyn_cast<MDNode>(V)) {
297        if (O->isFunctionLocal() && O->getFunction())
298          EnumerateFunctionLocalMetadata(O);
299      } else if (isa<Instruction>(V) || isa<Argument>(V))
300        EnumerateValue(V);
301    }
302
303  // Also, collect all function-local MDNodes for easy access.
304  FunctionLocalMDs.push_back(N);
305}
306
307void ValueEnumerator::EnumerateValue(const Value *V) {
308  assert(!V->getType()->isVoidTy() && "Can't insert void values!");
309  assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
310         "EnumerateValue doesn't handle Metadata!");
311
312  // Check to see if it's already in!
313  unsigned &ValueID = ValueMap[V];
314  if (ValueID) {
315    // Increment use count.
316    Values[ValueID-1].second++;
317    return;
318  }
319
320  // Enumerate the type of this value.
321  EnumerateType(V->getType());
322
323  if (const Constant *C = dyn_cast<Constant>(V)) {
324    if (isa<GlobalValue>(C)) {
325      // Initializers for globals are handled explicitly elsewhere.
326    } else if (C->getNumOperands()) {
327      // If a constant has operands, enumerate them.  This makes sure that if a
328      // constant has uses (for example an array of const ints), that they are
329      // inserted also.
330
331      // We prefer to enumerate them with values before we enumerate the user
332      // itself.  This makes it more likely that we can avoid forward references
333      // in the reader.  We know that there can be no cycles in the constants
334      // graph that don't go through a global variable.
335      for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
336           I != E; ++I)
337        if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
338          EnumerateValue(*I);
339
340      // Finally, add the value.  Doing this could make the ValueID reference be
341      // dangling, don't reuse it.
342      Values.push_back(std::make_pair(V, 1U));
343      ValueMap[V] = Values.size();
344      return;
345    }
346  }
347
348  // Add the value.
349  Values.push_back(std::make_pair(V, 1U));
350  ValueID = Values.size();
351}
352
353
354void ValueEnumerator::EnumerateType(Type *Ty) {
355  unsigned *TypeID = &TypeMap[Ty];
356
357  // We've already seen this type.
358  if (*TypeID)
359    return;
360
361  // If it is a non-anonymous struct, mark the type as being visited so that we
362  // don't recursively visit it.  This is safe because we allow forward
363  // references of these in the bitcode reader.
364  if (StructType *STy = dyn_cast<StructType>(Ty))
365    if (!STy->isLiteral())
366      *TypeID = ~0U;
367
368  // Enumerate all of the subtypes before we enumerate this type.  This ensures
369  // that the type will be enumerated in an order that can be directly built.
370  for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
371       I != E; ++I)
372    EnumerateType(*I);
373
374  // Refresh the TypeID pointer in case the table rehashed.
375  TypeID = &TypeMap[Ty];
376
377  // Check to see if we got the pointer another way.  This can happen when
378  // enumerating recursive types that hit the base case deeper than they start.
379  //
380  // If this is actually a struct that we are treating as forward ref'able,
381  // then emit the definition now that all of its contents are available.
382  if (*TypeID && *TypeID != ~0U)
383    return;
384
385  // Add this type now that its contents are all happily enumerated.
386  Types.push_back(Ty);
387
388  *TypeID = Types.size();
389}
390
391// Enumerate the types for the specified value.  If the value is a constant,
392// walk through it, enumerating the types of the constant.
393void ValueEnumerator::EnumerateOperandType(const Value *V) {
394  EnumerateType(V->getType());
395
396  if (const Constant *C = dyn_cast<Constant>(V)) {
397    // If this constant is already enumerated, ignore it, we know its type must
398    // be enumerated.
399    if (ValueMap.count(V)) return;
400
401    // This constant may have operands, make sure to enumerate the types in
402    // them.
403    for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
404      const Value *Op = C->getOperand(i);
405
406      // Don't enumerate basic blocks here, this happens as operands to
407      // blockaddress.
408      if (isa<BasicBlock>(Op)) continue;
409
410      EnumerateOperandType(Op);
411    }
412
413    if (const MDNode *N = dyn_cast<MDNode>(V)) {
414      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
415        if (Value *Elem = N->getOperand(i))
416          EnumerateOperandType(Elem);
417    }
418  } else if (isa<MDString>(V) || isa<MDNode>(V))
419    EnumerateMetadata(V);
420}
421
422void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
423  if (PAL.isEmpty()) return;  // null is always 0.
424  // Do a lookup.
425  unsigned &Entry = AttributeMap[PAL.getRawPointer()];
426  if (Entry == 0) {
427    // Never saw this before, add it.
428    Attributes.push_back(PAL);
429    Entry = Attributes.size();
430  }
431}
432
433void ValueEnumerator::incorporateFunction(const Function &F) {
434  InstructionCount = 0;
435  NumModuleValues = Values.size();
436  NumModuleMDValues = MDValues.size();
437
438  // Adding function arguments to the value table.
439  for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
440       I != E; ++I)
441    EnumerateValue(I);
442
443  FirstFuncConstantID = Values.size();
444
445  // Add all function-level constants to the value table.
446  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
447    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
448      for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
449           OI != E; ++OI) {
450        if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
451            isa<InlineAsm>(*OI))
452          EnumerateValue(*OI);
453      }
454    BasicBlocks.push_back(BB);
455    ValueMap[BB] = BasicBlocks.size();
456  }
457
458  // Optimize the constant layout.
459  OptimizeConstants(FirstFuncConstantID, Values.size());
460
461  // Add the function's parameter attributes so they are available for use in
462  // the function's instruction.
463  EnumerateAttributes(F.getAttributes());
464
465  FirstInstID = Values.size();
466
467  SmallVector<MDNode *, 8> FnLocalMDVector;
468  // Add all of the instructions.
469  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
470    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
471      for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
472           OI != E; ++OI) {
473        if (MDNode *MD = dyn_cast<MDNode>(*OI))
474          if (MD->isFunctionLocal() && MD->getFunction())
475            // Enumerate metadata after the instructions they might refer to.
476            FnLocalMDVector.push_back(MD);
477      }
478
479      SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
480      I->getAllMetadataOtherThanDebugLoc(MDs);
481      for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
482        MDNode *N = MDs[i].second;
483        if (N->isFunctionLocal() && N->getFunction())
484          FnLocalMDVector.push_back(N);
485      }
486
487      if (!I->getType()->isVoidTy())
488        EnumerateValue(I);
489    }
490  }
491
492  // Add all of the function-local metadata.
493  for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
494    EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
495}
496
497void ValueEnumerator::purgeFunction() {
498  /// Remove purged values from the ValueMap.
499  for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
500    ValueMap.erase(Values[i].first);
501  for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
502    MDValueMap.erase(MDValues[i].first);
503  for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
504    ValueMap.erase(BasicBlocks[i]);
505
506  Values.resize(NumModuleValues);
507  MDValues.resize(NumModuleMDValues);
508  BasicBlocks.clear();
509  FunctionLocalMDs.clear();
510}
511
512static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
513                                 DenseMap<const BasicBlock*, unsigned> &IDMap) {
514  unsigned Counter = 0;
515  for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
516    IDMap[BB] = ++Counter;
517}
518
519/// getGlobalBasicBlockID - This returns the function-specific ID for the
520/// specified basic block.  This is relatively expensive information, so it
521/// should only be used by rare constructs such as address-of-label.
522unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
523  unsigned &Idx = GlobalBasicBlockIDs[BB];
524  if (Idx != 0)
525    return Idx-1;
526
527  IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
528  return getGlobalBasicBlockID(BB);
529}
530
531}  // end llvm_3_2 namespace
532