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/STLExtras.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/IR/Constants.h"
18#include "llvm/IR/DerivedTypes.h"
19#include "llvm/IR/Instructions.h"
20#include "llvm/IR/Module.h"
21#include "llvm/IR/ValueSymbolTable.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 isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
30  return V.first->getType()->isIntOrIntVectorTy();
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 and vector of integer constants are at the start of the
198  // constant pool.  This is important so that GEP structure indices come before
199  // gep constant exprs.
200  std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
201                 isIntOrIntVectorValue);
202
203  // Rebuild the modified portion of ValueMap.
204  for (; CstStart != CstEnd; ++CstStart)
205    ValueMap[Values[CstStart].first] = CstStart+1;
206}
207
208
209/// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
210/// table into the values table.
211void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
212  for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
213       VI != VE; ++VI)
214    EnumerateValue(VI->getValue());
215}
216
217/// EnumerateNamedMetadata - Insert all of the values referenced by
218/// named metadata in the specified module.
219void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
220  for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
221       E = M->named_metadata_end(); I != E; ++I)
222    EnumerateNamedMDNode(I);
223}
224
225void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
226  for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
227    EnumerateMetadata(MD->getOperand(i));
228}
229
230/// EnumerateMDNodeOperands - Enumerate all non-function-local values
231/// and types referenced by the given MDNode.
232void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
233  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
234    if (Value *V = N->getOperand(i)) {
235      if (isa<MDNode>(V) || isa<MDString>(V))
236        EnumerateMetadata(V);
237      else if (!isa<Instruction>(V) && !isa<Argument>(V))
238        EnumerateValue(V);
239    } else
240      EnumerateType(Type::getVoidTy(N->getContext()));
241  }
242}
243
244void ValueEnumerator::EnumerateMetadata(const Value *MD) {
245  assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
246
247  // Enumerate the type of this value.
248  EnumerateType(MD->getType());
249
250  const MDNode *N = dyn_cast<MDNode>(MD);
251
252  // In the module-level pass, skip function-local nodes themselves, but
253  // do walk their operands.
254  if (N && N->isFunctionLocal() && N->getFunction()) {
255    EnumerateMDNodeOperands(N);
256    return;
257  }
258
259  // Check to see if it's already in!
260  unsigned &MDValueID = MDValueMap[MD];
261  if (MDValueID) {
262    // Increment use count.
263    MDValues[MDValueID-1].second++;
264    return;
265  }
266  MDValues.push_back(std::make_pair(MD, 1U));
267  MDValueID = MDValues.size();
268
269  // Enumerate all non-function-local operands.
270  if (N)
271    EnumerateMDNodeOperands(N);
272}
273
274/// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
275/// information reachable from the given MDNode.
276void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
277  assert(N->isFunctionLocal() && N->getFunction() &&
278         "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
279
280  // Enumerate the type of this value.
281  EnumerateType(N->getType());
282
283  // Check to see if it's already in!
284  unsigned &MDValueID = MDValueMap[N];
285  if (MDValueID) {
286    // Increment use count.
287    MDValues[MDValueID-1].second++;
288    return;
289  }
290  MDValues.push_back(std::make_pair(N, 1U));
291  MDValueID = MDValues.size();
292
293  // To incoroporate function-local information visit all function-local
294  // MDNodes and all function-local values they reference.
295  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
296    if (Value *V = N->getOperand(i)) {
297      if (MDNode *O = dyn_cast<MDNode>(V)) {
298        if (O->isFunctionLocal() && O->getFunction())
299          EnumerateFunctionLocalMetadata(O);
300      } else if (isa<Instruction>(V) || isa<Argument>(V))
301        EnumerateValue(V);
302    }
303
304  // Also, collect all function-local MDNodes for easy access.
305  FunctionLocalMDs.push_back(N);
306}
307
308void ValueEnumerator::EnumerateValue(const Value *V) {
309  assert(!V->getType()->isVoidTy() && "Can't insert void values!");
310  assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
311         "EnumerateValue doesn't handle Metadata!");
312
313  // Check to see if it's already in!
314  unsigned &ValueID = ValueMap[V];
315  if (ValueID) {
316    // Increment use count.
317    Values[ValueID-1].second++;
318    return;
319  }
320
321  // Enumerate the type of this value.
322  EnumerateType(V->getType());
323
324  if (const Constant *C = dyn_cast<Constant>(V)) {
325    if (isa<GlobalValue>(C)) {
326      // Initializers for globals are handled explicitly elsewhere.
327    } else if (C->getNumOperands()) {
328      // If a constant has operands, enumerate them.  This makes sure that if a
329      // constant has uses (for example an array of const ints), that they are
330      // inserted also.
331
332      // We prefer to enumerate them with values before we enumerate the user
333      // itself.  This makes it more likely that we can avoid forward references
334      // in the reader.  We know that there can be no cycles in the constants
335      // graph that don't go through a global variable.
336      for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
337           I != E; ++I)
338        if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
339          EnumerateValue(*I);
340
341      // Finally, add the value.  Doing this could make the ValueID reference be
342      // dangling, don't reuse it.
343      Values.push_back(std::make_pair(V, 1U));
344      ValueMap[V] = Values.size();
345      return;
346    }
347  }
348
349  // Add the value.
350  Values.push_back(std::make_pair(V, 1U));
351  ValueID = Values.size();
352}
353
354
355void ValueEnumerator::EnumerateType(Type *Ty) {
356  unsigned *TypeID = &TypeMap[Ty];
357
358  // We've already seen this type.
359  if (*TypeID)
360    return;
361
362  // If it is a non-anonymous struct, mark the type as being visited so that we
363  // don't recursively visit it.  This is safe because we allow forward
364  // references of these in the bitcode reader.
365  if (StructType *STy = dyn_cast<StructType>(Ty))
366    if (!STy->isLiteral())
367      *TypeID = ~0U;
368
369  // Enumerate all of the subtypes before we enumerate this type.  This ensures
370  // that the type will be enumerated in an order that can be directly built.
371  for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
372       I != E; ++I)
373    EnumerateType(*I);
374
375  // Refresh the TypeID pointer in case the table rehashed.
376  TypeID = &TypeMap[Ty];
377
378  // Check to see if we got the pointer another way.  This can happen when
379  // enumerating recursive types that hit the base case deeper than they start.
380  //
381  // If this is actually a struct that we are treating as forward ref'able,
382  // then emit the definition now that all of its contents are available.
383  if (*TypeID && *TypeID != ~0U)
384    return;
385
386  // Add this type now that its contents are all happily enumerated.
387  Types.push_back(Ty);
388
389  *TypeID = Types.size();
390}
391
392// Enumerate the types for the specified value.  If the value is a constant,
393// walk through it, enumerating the types of the constant.
394void ValueEnumerator::EnumerateOperandType(const Value *V) {
395  EnumerateType(V->getType());
396
397  if (const Constant *C = dyn_cast<Constant>(V)) {
398    // If this constant is already enumerated, ignore it, we know its type must
399    // be enumerated.
400    if (ValueMap.count(V)) return;
401
402    // This constant may have operands, make sure to enumerate the types in
403    // them.
404    for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
405      const Value *Op = C->getOperand(i);
406
407      // Don't enumerate basic blocks here, this happens as operands to
408      // blockaddress.
409      if (isa<BasicBlock>(Op)) continue;
410
411      EnumerateOperandType(Op);
412    }
413
414    if (const MDNode *N = dyn_cast<MDNode>(V)) {
415      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
416        if (Value *Elem = N->getOperand(i))
417          EnumerateOperandType(Elem);
418    }
419  } else if (isa<MDString>(V) || isa<MDNode>(V))
420    EnumerateMetadata(V);
421}
422
423void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
424  if (PAL.isEmpty()) return;  // null is always 0.
425
426  // Do a lookup.
427  unsigned &Entry = AttributeMap[PAL];
428  if (Entry == 0) {
429    // Never saw this before, add it.
430    Attribute.push_back(PAL);
431    Entry = Attribute.size();
432  }
433
434  // Do lookups for all attribute groups.
435  for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
436    AttributeSet AS = PAL.getSlotAttributes(i);
437    unsigned &Entry = AttributeGroupMap[AS];
438    if (Entry == 0) {
439      AttributeGroups.push_back(AS);
440      Entry = AttributeGroups.size();
441    }
442  }
443}
444
445void ValueEnumerator::incorporateFunction(const Function &F) {
446  InstructionCount = 0;
447  NumModuleValues = Values.size();
448  NumModuleMDValues = MDValues.size();
449
450  // Adding function arguments to the value table.
451  for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
452       I != E; ++I)
453    EnumerateValue(I);
454
455  FirstFuncConstantID = Values.size();
456
457  // Add all function-level constants to the value table.
458  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
459    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
460      for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
461           OI != E; ++OI) {
462        if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
463            isa<InlineAsm>(*OI))
464          EnumerateValue(*OI);
465      }
466    BasicBlocks.push_back(BB);
467    ValueMap[BB] = BasicBlocks.size();
468  }
469
470  // Optimize the constant layout.
471  OptimizeConstants(FirstFuncConstantID, Values.size());
472
473  // Add the function's parameter attributes so they are available for use in
474  // the function's instruction.
475  EnumerateAttributes(F.getAttributes());
476
477  FirstInstID = Values.size();
478
479  SmallVector<MDNode *, 8> FnLocalMDVector;
480  // Add all of the instructions.
481  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
482    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
483      for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
484           OI != E; ++OI) {
485        if (MDNode *MD = dyn_cast<MDNode>(*OI))
486          if (MD->isFunctionLocal() && MD->getFunction())
487            // Enumerate metadata after the instructions they might refer to.
488            FnLocalMDVector.push_back(MD);
489      }
490
491      SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
492      I->getAllMetadataOtherThanDebugLoc(MDs);
493      for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
494        MDNode *N = MDs[i].second;
495        if (N->isFunctionLocal() && N->getFunction())
496          FnLocalMDVector.push_back(N);
497      }
498
499      if (!I->getType()->isVoidTy())
500        EnumerateValue(I);
501    }
502  }
503
504  // Add all of the function-local metadata.
505  for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
506    EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
507}
508
509void ValueEnumerator::purgeFunction() {
510  /// Remove purged values from the ValueMap.
511  for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
512    ValueMap.erase(Values[i].first);
513  for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
514    MDValueMap.erase(MDValues[i].first);
515  for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
516    ValueMap.erase(BasicBlocks[i]);
517
518  Values.resize(NumModuleValues);
519  MDValues.resize(NumModuleMDValues);
520  BasicBlocks.clear();
521  FunctionLocalMDs.clear();
522}
523
524static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
525                                 DenseMap<const BasicBlock*, unsigned> &IDMap) {
526  unsigned Counter = 0;
527  for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
528    IDMap[BB] = ++Counter;
529}
530
531/// getGlobalBasicBlockID - This returns the function-specific ID for the
532/// specified basic block.  This is relatively expensive information, so it
533/// should only be used by rare constructs such as address-of-label.
534unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
535  unsigned &Idx = GlobalBasicBlockIDs[BB];
536  if (Idx != 0)
537    return Idx-1;
538
539  IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
540  return getGlobalBasicBlockID(BB);
541}
542
543}  // end llvm_3_2 namespace
544