ValueEnumerator.cpp revision db37c900ebe6f0ae62a1f77327dd9e5a469ff11e
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_2_9 {
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    } else if (const ConstantDataSequential *CDS =
346               dyn_cast<ConstantDataSequential>(C)) {
347      // For our legacy handling of the new ConstantDataSequential type, we
348      // need to enumerate the individual elements, as well as mark the
349      // outer constant as used.
350      for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
351        EnumerateValue(CDS->getElementAsConstant(i));
352      Values.push_back(std::make_pair(V, 1U));
353      ValueMap[V] = Values.size();
354      return;
355    }
356  }
357
358  // Add the value.
359  Values.push_back(std::make_pair(V, 1U));
360  ValueID = Values.size();
361}
362
363
364void ValueEnumerator::EnumerateType(Type *Ty) {
365  unsigned *TypeID = &TypeMap[Ty];
366
367  // We've already seen this type.
368  if (*TypeID)
369    return;
370
371  // If it is a non-anonymous struct, mark the type as being visited so that we
372  // don't recursively visit it.  This is safe because we allow forward
373  // references of these in the bitcode reader.
374  if (StructType *STy = dyn_cast<StructType>(Ty))
375    if (!STy->isLiteral())
376      *TypeID = ~0U;
377
378  // Enumerate all of the subtypes before we enumerate this type.  This ensures
379  // that the type will be enumerated in an order that can be directly built.
380  for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
381       I != E; ++I)
382    EnumerateType(*I);
383
384  // Refresh the TypeID pointer in case the table rehashed.
385  TypeID = &TypeMap[Ty];
386
387  // Check to see if we got the pointer another way.  This can happen when
388  // enumerating recursive types that hit the base case deeper than they start.
389  //
390  // If this is actually a struct that we are treating as forward ref'able,
391  // then emit the definition now that all of its contents are available.
392  if (*TypeID && *TypeID != ~0U)
393    return;
394
395  // Add this type now that its contents are all happily enumerated.
396  Types.push_back(Ty);
397
398  *TypeID = Types.size();
399}
400
401// Enumerate the types for the specified value.  If the value is a constant,
402// walk through it, enumerating the types of the constant.
403void ValueEnumerator::EnumerateOperandType(const Value *V) {
404  EnumerateType(V->getType());
405
406  if (const Constant *C = dyn_cast<Constant>(V)) {
407    // If this constant is already enumerated, ignore it, we know its type must
408    // be enumerated.
409    if (ValueMap.count(V)) return;
410
411    // This constant may have operands, make sure to enumerate the types in
412    // them.
413    for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
414      const Value *Op = C->getOperand(i);
415
416      // Don't enumerate basic blocks here, this happens as operands to
417      // blockaddress.
418      if (isa<BasicBlock>(Op)) continue;
419
420      EnumerateOperandType(Op);
421    }
422
423    if (const MDNode *N = dyn_cast<MDNode>(V)) {
424      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
425        if (Value *Elem = N->getOperand(i))
426          EnumerateOperandType(Elem);
427    }
428  } else if (isa<MDString>(V) || isa<MDNode>(V))
429    EnumerateMetadata(V);
430}
431
432void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
433  if (PAL.isEmpty()) return;  // null is always 0.
434  // Do a lookup.
435  unsigned &Entry = AttributeMap[PAL.getRawPointer()];
436  if (Entry == 0) {
437    // Never saw this before, add it.
438    Attributes.push_back(PAL);
439    Entry = Attributes.size();
440  }
441}
442
443void ValueEnumerator::incorporateFunction(const Function &F) {
444  InstructionCount = 0;
445  NumModuleValues = Values.size();
446  NumModuleMDValues = MDValues.size();
447
448  // Adding function arguments to the value table.
449  for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
450       I != E; ++I)
451    EnumerateValue(I);
452
453  FirstFuncConstantID = Values.size();
454
455  // Add all function-level constants to the value table.
456  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
457    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
458      for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
459           OI != E; ++OI) {
460        if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
461            isa<InlineAsm>(*OI))
462          EnumerateValue(*OI);
463      }
464    BasicBlocks.push_back(BB);
465    ValueMap[BB] = BasicBlocks.size();
466  }
467
468  // Optimize the constant layout.
469  OptimizeConstants(FirstFuncConstantID, Values.size());
470
471  // Add the function's parameter attributes so they are available for use in
472  // the function's instruction.
473  EnumerateAttributes(F.getAttributes());
474
475  FirstInstID = Values.size();
476
477  SmallVector<MDNode *, 8> FnLocalMDVector;
478  // Add all of the instructions.
479  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
480    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
481      for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
482           OI != E; ++OI) {
483        if (MDNode *MD = dyn_cast<MDNode>(*OI))
484          if (MD->isFunctionLocal() && MD->getFunction())
485            // Enumerate metadata after the instructions they might refer to.
486            FnLocalMDVector.push_back(MD);
487      }
488
489      SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
490      I->getAllMetadataOtherThanDebugLoc(MDs);
491      for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
492        MDNode *N = MDs[i].second;
493        if (N->isFunctionLocal() && N->getFunction())
494          FnLocalMDVector.push_back(N);
495      }
496
497      if (!I->getType()->isVoidTy())
498        EnumerateValue(I);
499    }
500  }
501
502  // Add all of the function-local metadata.
503  for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
504    EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
505}
506
507void ValueEnumerator::purgeFunction() {
508  /// Remove purged values from the ValueMap.
509  for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
510    ValueMap.erase(Values[i].first);
511  for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
512    MDValueMap.erase(MDValues[i].first);
513  for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
514    ValueMap.erase(BasicBlocks[i]);
515
516  Values.resize(NumModuleValues);
517  MDValues.resize(NumModuleMDValues);
518  BasicBlocks.clear();
519  FunctionLocalMDs.clear();
520}
521
522static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
523                                 DenseMap<const BasicBlock*, unsigned> &IDMap) {
524  unsigned Counter = 0;
525  for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
526    IDMap[BB] = ++Counter;
527}
528
529/// getGlobalBasicBlockID - This returns the function-specific ID for the
530/// specified basic block.  This is relatively expensive information, so it
531/// should only be used by rare constructs such as address-of-label.
532unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
533  unsigned &Idx = GlobalBasicBlockIDs[BB];
534  if (Idx != 0)
535    return Idx-1;
536
537  IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
538  return getGlobalBasicBlockID(BB);
539}
540
541} // end llvm_2_9 namespace
542