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