MachineModuleInfo.cpp revision 73ef58ab92d5cd23b119b7f206e5f8a8c529098d
1//===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by James M. Laskey and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/CodeGen/MachineModuleInfo.h"
11
12#include "llvm/Constants.h"
13#include "llvm/CodeGen/MachineFunctionPass.h"
14#include "llvm/CodeGen/MachineFunction.h"
15#include "llvm/CodeGen/MachineLocation.h"
16#include "llvm/Target/TargetInstrInfo.h"
17#include "llvm/Target/TargetMachine.h"
18#include "llvm/Target/TargetOptions.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/GlobalVariable.h"
21#include "llvm/Intrinsics.h"
22#include "llvm/Instructions.h"
23#include "llvm/Module.h"
24#include "llvm/Support/Dwarf.h"
25#include "llvm/Support/Streams.h"
26using namespace llvm;
27using namespace llvm::dwarf;
28
29// Handle the Pass registration stuff necessary to use TargetData's.
30namespace {
31  RegisterPass<MachineModuleInfo> X("machinemoduleinfo", "Module Information");
32}
33char MachineModuleInfo::ID = 0;
34
35//===----------------------------------------------------------------------===//
36
37/// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
38/// specified value in their initializer somewhere.
39static void
40getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
41  // Scan though value users.
42  for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
43    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
44      // If the user is a GlobalVariable then add to result.
45      Result.push_back(GV);
46    } else if (Constant *C = dyn_cast<Constant>(*I)) {
47      // If the user is a constant variable then scan its users
48      getGlobalVariablesUsing(C, Result);
49    }
50  }
51}
52
53/// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
54/// named GlobalVariable.
55static std::vector<GlobalVariable*>
56getGlobalVariablesUsing(Module &M, const std::string &RootName) {
57  std::vector<GlobalVariable*> Result;  // GlobalVariables matching criteria.
58
59  std::vector<const Type*> FieldTypes;
60  FieldTypes.push_back(Type::Int32Ty);
61  FieldTypes.push_back(Type::Int32Ty);
62
63  // Get the GlobalVariable root.
64  GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
65                                                StructType::get(FieldTypes));
66
67  // If present and linkonce then scan for users.
68  if (UseRoot && UseRoot->hasLinkOnceLinkage()) {
69    getGlobalVariablesUsing(UseRoot, Result);
70  }
71
72  return Result;
73}
74
75/// isStringValue - Return true if the given value can be coerced to a string.
76///
77static bool isStringValue(Value *V) {
78  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
79    if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
80      ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
81      return Init->isString();
82    }
83  } else if (Constant *C = dyn_cast<Constant>(V)) {
84    if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
85      return isStringValue(GV);
86    else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
87      if (CE->getOpcode() == Instruction::GetElementPtr) {
88        if (CE->getNumOperands() == 3 &&
89            cast<Constant>(CE->getOperand(1))->isNullValue() &&
90            isa<ConstantInt>(CE->getOperand(2))) {
91          return isStringValue(CE->getOperand(0));
92        }
93      }
94    }
95  }
96  return false;
97}
98
99/// getGlobalVariable - Return either a direct or cast Global value.
100///
101static GlobalVariable *getGlobalVariable(Value *V) {
102  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
103    return GV;
104  } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
105    if (CE->getOpcode() == Instruction::BitCast) {
106      return dyn_cast<GlobalVariable>(CE->getOperand(0));
107    }
108  }
109  return NULL;
110}
111
112/// isGlobalVariable - Return true if the given value can be coerced to a
113/// GlobalVariable.
114static bool isGlobalVariable(Value *V) {
115  if (isa<GlobalVariable>(V) || isa<ConstantPointerNull>(V)) {
116    return true;
117  } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
118    if (CE->getOpcode() == Instruction::BitCast) {
119      return isa<GlobalVariable>(CE->getOperand(0));
120    }
121  }
122  return false;
123}
124
125/// getUIntOperand - Return ith operand if it is an unsigned integer.
126///
127static ConstantInt *getUIntOperand(GlobalVariable *GV, unsigned i) {
128  // Make sure the GlobalVariable has an initializer.
129  if (!GV->hasInitializer()) return NULL;
130
131  // Get the initializer constant.
132  ConstantStruct *CI = dyn_cast<ConstantStruct>(GV->getInitializer());
133  if (!CI) return NULL;
134
135  // Check if there is at least i + 1 operands.
136  unsigned N = CI->getNumOperands();
137  if (i >= N) return NULL;
138
139  // Check constant.
140  return dyn_cast<ConstantInt>(CI->getOperand(i));
141}
142
143//===----------------------------------------------------------------------===//
144
145/// ApplyToFields - Target the visitor to each field of the debug information
146/// descriptor.
147void DIVisitor::ApplyToFields(DebugInfoDesc *DD) {
148  DD->ApplyToFields(this);
149}
150
151//===----------------------------------------------------------------------===//
152/// DICountVisitor - This DIVisitor counts all the fields in the supplied debug
153/// the supplied DebugInfoDesc.
154class DICountVisitor : public DIVisitor {
155private:
156  unsigned Count;                       // Running count of fields.
157
158public:
159  DICountVisitor() : DIVisitor(), Count(0) {}
160
161  // Accessors.
162  unsigned getCount() const { return Count; }
163
164  /// Apply - Count each of the fields.
165  ///
166  virtual void Apply(int &Field)             { ++Count; }
167  virtual void Apply(unsigned &Field)        { ++Count; }
168  virtual void Apply(int64_t &Field)         { ++Count; }
169  virtual void Apply(uint64_t &Field)        { ++Count; }
170  virtual void Apply(bool &Field)            { ++Count; }
171  virtual void Apply(std::string &Field)     { ++Count; }
172  virtual void Apply(DebugInfoDesc *&Field)  { ++Count; }
173  virtual void Apply(GlobalVariable *&Field) { ++Count; }
174  virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
175    ++Count;
176  }
177};
178
179//===----------------------------------------------------------------------===//
180/// DIDeserializeVisitor - This DIVisitor deserializes all the fields in the
181/// supplied DebugInfoDesc.
182class DIDeserializeVisitor : public DIVisitor {
183private:
184  DIDeserializer &DR;                   // Active deserializer.
185  unsigned I;                           // Current operand index.
186  ConstantStruct *CI;                   // GlobalVariable constant initializer.
187
188public:
189  DIDeserializeVisitor(DIDeserializer &D, GlobalVariable *GV)
190  : DIVisitor()
191  , DR(D)
192  , I(0)
193  , CI(cast<ConstantStruct>(GV->getInitializer()))
194  {}
195
196  /// Apply - Set the value of each of the fields.
197  ///
198  virtual void Apply(int &Field) {
199    Constant *C = CI->getOperand(I++);
200    Field = cast<ConstantInt>(C)->getSExtValue();
201  }
202  virtual void Apply(unsigned &Field) {
203    Constant *C = CI->getOperand(I++);
204    Field = cast<ConstantInt>(C)->getZExtValue();
205  }
206  virtual void Apply(int64_t &Field) {
207    Constant *C = CI->getOperand(I++);
208    Field = cast<ConstantInt>(C)->getSExtValue();
209  }
210  virtual void Apply(uint64_t &Field) {
211    Constant *C = CI->getOperand(I++);
212    Field = cast<ConstantInt>(C)->getZExtValue();
213  }
214  virtual void Apply(bool &Field) {
215    Constant *C = CI->getOperand(I++);
216    Field = cast<ConstantInt>(C)->getZExtValue();
217  }
218  virtual void Apply(std::string &Field) {
219    Constant *C = CI->getOperand(I++);
220    Field = C->getStringValue();
221  }
222  virtual void Apply(DebugInfoDesc *&Field) {
223    Constant *C = CI->getOperand(I++);
224    Field = DR.Deserialize(C);
225  }
226  virtual void Apply(GlobalVariable *&Field) {
227    Constant *C = CI->getOperand(I++);
228    Field = getGlobalVariable(C);
229  }
230  virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
231    Field.resize(0);
232    Constant *C = CI->getOperand(I++);
233    GlobalVariable *GV = getGlobalVariable(C);
234    if (GV->hasInitializer()) {
235      if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
236        for (unsigned i = 0, N = CA->getNumOperands(); i < N; ++i) {
237          GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
238          DebugInfoDesc *DE = DR.Deserialize(GVE);
239          Field.push_back(DE);
240        }
241      } else if (GV->getInitializer()->isNullValue()) {
242        if (const ArrayType *T =
243            dyn_cast<ArrayType>(GV->getType()->getElementType())) {
244          Field.resize(T->getNumElements());
245        }
246      }
247    }
248  }
249};
250
251//===----------------------------------------------------------------------===//
252/// DISerializeVisitor - This DIVisitor serializes all the fields in
253/// the supplied DebugInfoDesc.
254class DISerializeVisitor : public DIVisitor {
255private:
256  DISerializer &SR;                     // Active serializer.
257  std::vector<Constant*> &Elements;     // Element accumulator.
258
259public:
260  DISerializeVisitor(DISerializer &S, std::vector<Constant*> &E)
261  : DIVisitor()
262  , SR(S)
263  , Elements(E)
264  {}
265
266  /// Apply - Set the value of each of the fields.
267  ///
268  virtual void Apply(int &Field) {
269    Elements.push_back(ConstantInt::get(Type::Int32Ty, int32_t(Field)));
270  }
271  virtual void Apply(unsigned &Field) {
272    Elements.push_back(ConstantInt::get(Type::Int32Ty, uint32_t(Field)));
273  }
274  virtual void Apply(int64_t &Field) {
275    Elements.push_back(ConstantInt::get(Type::Int64Ty, int64_t(Field)));
276  }
277  virtual void Apply(uint64_t &Field) {
278    Elements.push_back(ConstantInt::get(Type::Int64Ty, uint64_t(Field)));
279  }
280  virtual void Apply(bool &Field) {
281    Elements.push_back(ConstantInt::get(Type::Int1Ty, Field));
282  }
283  virtual void Apply(std::string &Field) {
284      Elements.push_back(SR.getString(Field));
285  }
286  virtual void Apply(DebugInfoDesc *&Field) {
287    GlobalVariable *GV = NULL;
288
289    // If non-NULL then convert to global.
290    if (Field) GV = SR.Serialize(Field);
291
292    // FIXME - At some point should use specific type.
293    const PointerType *EmptyTy = SR.getEmptyStructPtrType();
294
295    if (GV) {
296      // Set to pointer to global.
297      Elements.push_back(ConstantExpr::getBitCast(GV, EmptyTy));
298    } else {
299      // Use NULL.
300      Elements.push_back(ConstantPointerNull::get(EmptyTy));
301    }
302  }
303  virtual void Apply(GlobalVariable *&Field) {
304    const PointerType *EmptyTy = SR.getEmptyStructPtrType();
305    if (Field) {
306      Elements.push_back(ConstantExpr::getBitCast(Field, EmptyTy));
307    } else {
308      Elements.push_back(ConstantPointerNull::get(EmptyTy));
309    }
310  }
311  virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
312    const PointerType *EmptyTy = SR.getEmptyStructPtrType();
313    unsigned N = Field.size();
314    ArrayType *AT = ArrayType::get(EmptyTy, N);
315    std::vector<Constant *> ArrayElements;
316
317    for (unsigned i = 0, N = Field.size(); i < N; ++i) {
318      if (DebugInfoDesc *Element = Field[i]) {
319        GlobalVariable *GVE = SR.Serialize(Element);
320        Constant *CE = ConstantExpr::getBitCast(GVE, EmptyTy);
321        ArrayElements.push_back(cast<Constant>(CE));
322      } else {
323        ArrayElements.push_back(ConstantPointerNull::get(EmptyTy));
324      }
325    }
326
327    Constant *CA = ConstantArray::get(AT, ArrayElements);
328    GlobalVariable *CAGV = new GlobalVariable(AT, true,
329                                              GlobalValue::InternalLinkage,
330                                              CA, "llvm.dbg.array",
331                                              SR.getModule());
332    CAGV->setSection("llvm.metadata");
333    Constant *CAE = ConstantExpr::getBitCast(CAGV, EmptyTy);
334    Elements.push_back(CAE);
335  }
336};
337
338//===----------------------------------------------------------------------===//
339/// DIGetTypesVisitor - This DIVisitor gathers all the field types in
340/// the supplied DebugInfoDesc.
341class DIGetTypesVisitor : public DIVisitor {
342private:
343  DISerializer &SR;                     // Active serializer.
344  std::vector<const Type*> &Fields;     // Type accumulator.
345
346public:
347  DIGetTypesVisitor(DISerializer &S, std::vector<const Type*> &F)
348  : DIVisitor()
349  , SR(S)
350  , Fields(F)
351  {}
352
353  /// Apply - Set the value of each of the fields.
354  ///
355  virtual void Apply(int &Field) {
356    Fields.push_back(Type::Int32Ty);
357  }
358  virtual void Apply(unsigned &Field) {
359    Fields.push_back(Type::Int32Ty);
360  }
361  virtual void Apply(int64_t &Field) {
362    Fields.push_back(Type::Int64Ty);
363  }
364  virtual void Apply(uint64_t &Field) {
365    Fields.push_back(Type::Int64Ty);
366  }
367  virtual void Apply(bool &Field) {
368    Fields.push_back(Type::Int1Ty);
369  }
370  virtual void Apply(std::string &Field) {
371    Fields.push_back(SR.getStrPtrType());
372  }
373  virtual void Apply(DebugInfoDesc *&Field) {
374    // FIXME - At some point should use specific type.
375    const PointerType *EmptyTy = SR.getEmptyStructPtrType();
376    Fields.push_back(EmptyTy);
377  }
378  virtual void Apply(GlobalVariable *&Field) {
379    const PointerType *EmptyTy = SR.getEmptyStructPtrType();
380    Fields.push_back(EmptyTy);
381  }
382  virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
383    const PointerType *EmptyTy = SR.getEmptyStructPtrType();
384    Fields.push_back(EmptyTy);
385  }
386};
387
388//===----------------------------------------------------------------------===//
389/// DIVerifyVisitor - This DIVisitor verifies all the field types against
390/// a constant initializer.
391class DIVerifyVisitor : public DIVisitor {
392private:
393  DIVerifier &VR;                       // Active verifier.
394  bool IsValid;                         // Validity status.
395  unsigned I;                           // Current operand index.
396  ConstantStruct *CI;                   // GlobalVariable constant initializer.
397
398public:
399  DIVerifyVisitor(DIVerifier &V, GlobalVariable *GV)
400  : DIVisitor()
401  , VR(V)
402  , IsValid(true)
403  , I(0)
404  , CI(cast<ConstantStruct>(GV->getInitializer()))
405  {
406  }
407
408  // Accessors.
409  bool isValid() const { return IsValid; }
410
411  /// Apply - Set the value of each of the fields.
412  ///
413  virtual void Apply(int &Field) {
414    Constant *C = CI->getOperand(I++);
415    IsValid = IsValid && isa<ConstantInt>(C);
416  }
417  virtual void Apply(unsigned &Field) {
418    Constant *C = CI->getOperand(I++);
419    IsValid = IsValid && isa<ConstantInt>(C);
420  }
421  virtual void Apply(int64_t &Field) {
422    Constant *C = CI->getOperand(I++);
423    IsValid = IsValid && isa<ConstantInt>(C);
424  }
425  virtual void Apply(uint64_t &Field) {
426    Constant *C = CI->getOperand(I++);
427    IsValid = IsValid && isa<ConstantInt>(C);
428  }
429  virtual void Apply(bool &Field) {
430    Constant *C = CI->getOperand(I++);
431    IsValid = IsValid && isa<ConstantInt>(C) && C->getType() == Type::Int1Ty;
432  }
433  virtual void Apply(std::string &Field) {
434    Constant *C = CI->getOperand(I++);
435    IsValid = IsValid &&
436              (!C || isStringValue(C) || C->isNullValue());
437  }
438  virtual void Apply(DebugInfoDesc *&Field) {
439    // FIXME - Prepare the correct descriptor.
440    Constant *C = CI->getOperand(I++);
441    IsValid = IsValid && isGlobalVariable(C);
442  }
443  virtual void Apply(GlobalVariable *&Field) {
444    Constant *C = CI->getOperand(I++);
445    IsValid = IsValid && isGlobalVariable(C);
446  }
447  virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
448    Constant *C = CI->getOperand(I++);
449    IsValid = IsValid && isGlobalVariable(C);
450    if (!IsValid) return;
451
452    GlobalVariable *GV = getGlobalVariable(C);
453    IsValid = IsValid && GV && GV->hasInitializer();
454    if (!IsValid) return;
455
456    ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
457    IsValid = IsValid && CA;
458    if (!IsValid) return;
459
460    for (unsigned i = 0, N = CA->getNumOperands(); IsValid && i < N; ++i) {
461      IsValid = IsValid && isGlobalVariable(CA->getOperand(i));
462      if (!IsValid) return;
463
464      GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
465      VR.Verify(GVE);
466    }
467  }
468};
469
470
471//===----------------------------------------------------------------------===//
472
473/// TagFromGlobal - Returns the tag number from a debug info descriptor
474/// GlobalVariable.   Return DIIValid if operand is not an unsigned int.
475unsigned DebugInfoDesc::TagFromGlobal(GlobalVariable *GV) {
476  ConstantInt *C = getUIntOperand(GV, 0);
477  return C ? ((unsigned)C->getZExtValue() & ~LLVMDebugVersionMask) :
478             (unsigned)DW_TAG_invalid;
479}
480
481/// VersionFromGlobal - Returns the version number from a debug info
482/// descriptor GlobalVariable.  Return DIIValid if operand is not an unsigned
483/// int.
484unsigned  DebugInfoDesc::VersionFromGlobal(GlobalVariable *GV) {
485  ConstantInt *C = getUIntOperand(GV, 0);
486  return C ? ((unsigned)C->getZExtValue() & LLVMDebugVersionMask) :
487             (unsigned)DW_TAG_invalid;
488}
489
490/// DescFactory - Create an instance of debug info descriptor based on Tag.
491/// Return NULL if not a recognized Tag.
492DebugInfoDesc *DebugInfoDesc::DescFactory(unsigned Tag) {
493  switch (Tag) {
494  case DW_TAG_anchor:           return new AnchorDesc();
495  case DW_TAG_compile_unit:     return new CompileUnitDesc();
496  case DW_TAG_variable:         return new GlobalVariableDesc();
497  case DW_TAG_subprogram:       return new SubprogramDesc();
498  case DW_TAG_lexical_block:    return new BlockDesc();
499  case DW_TAG_base_type:        return new BasicTypeDesc();
500  case DW_TAG_typedef:
501  case DW_TAG_pointer_type:
502  case DW_TAG_reference_type:
503  case DW_TAG_const_type:
504  case DW_TAG_volatile_type:
505  case DW_TAG_restrict_type:
506  case DW_TAG_member:
507  case DW_TAG_inheritance:      return new DerivedTypeDesc(Tag);
508  case DW_TAG_array_type:
509  case DW_TAG_structure_type:
510  case DW_TAG_union_type:
511  case DW_TAG_enumeration_type:
512  case DW_TAG_vector_type:
513  case DW_TAG_subroutine_type:  return new CompositeTypeDesc(Tag);
514  case DW_TAG_subrange_type:    return new SubrangeDesc();
515  case DW_TAG_enumerator:       return new EnumeratorDesc();
516  case DW_TAG_return_variable:
517  case DW_TAG_arg_variable:
518  case DW_TAG_auto_variable:    return new VariableDesc(Tag);
519  default: break;
520  }
521  return NULL;
522}
523
524/// getLinkage - get linkage appropriate for this type of descriptor.
525///
526GlobalValue::LinkageTypes DebugInfoDesc::getLinkage() const {
527  return GlobalValue::InternalLinkage;
528}
529
530/// ApplyToFields - Target the vistor to the fields of the descriptor.
531///
532void DebugInfoDesc::ApplyToFields(DIVisitor *Visitor) {
533  Visitor->Apply(Tag);
534}
535
536//===----------------------------------------------------------------------===//
537
538AnchorDesc::AnchorDesc()
539: DebugInfoDesc(DW_TAG_anchor)
540, AnchorTag(0)
541{}
542AnchorDesc::AnchorDesc(AnchoredDesc *D)
543: DebugInfoDesc(DW_TAG_anchor)
544, AnchorTag(D->getTag())
545{}
546
547// Implement isa/cast/dyncast.
548bool AnchorDesc::classof(const DebugInfoDesc *D) {
549  return D->getTag() == DW_TAG_anchor;
550}
551
552/// getLinkage - get linkage appropriate for this type of descriptor.
553///
554GlobalValue::LinkageTypes AnchorDesc::getLinkage() const {
555  return GlobalValue::LinkOnceLinkage;
556}
557
558/// ApplyToFields - Target the visitor to the fields of the TransUnitDesc.
559///
560void AnchorDesc::ApplyToFields(DIVisitor *Visitor) {
561  DebugInfoDesc::ApplyToFields(Visitor);
562
563  Visitor->Apply(AnchorTag);
564}
565
566/// getDescString - Return a string used to compose global names and labels. A
567/// A global variable name needs to be defined for each debug descriptor that is
568/// anchored. NOTE: that each global variable named here also needs to be added
569/// to the list of names left external in the internalizer.
570///   ExternalNames.insert("llvm.dbg.compile_units");
571///   ExternalNames.insert("llvm.dbg.global_variables");
572///   ExternalNames.insert("llvm.dbg.subprograms");
573const char *AnchorDesc::getDescString() const {
574  switch (AnchorTag) {
575  case DW_TAG_compile_unit: return CompileUnitDesc::AnchorString;
576  case DW_TAG_variable:     return GlobalVariableDesc::AnchorString;
577  case DW_TAG_subprogram:   return SubprogramDesc::AnchorString;
578  default: break;
579  }
580
581  assert(0 && "Tag does not have a case for anchor string");
582  return "";
583}
584
585/// getTypeString - Return a string used to label this descriptors type.
586///
587const char *AnchorDesc::getTypeString() const {
588  return "llvm.dbg.anchor.type";
589}
590
591#ifndef NDEBUG
592void AnchorDesc::dump() {
593  cerr << getDescString() << " "
594       << "Version(" << getVersion() << "), "
595       << "Tag(" << getTag() << "), "
596       << "AnchorTag(" << AnchorTag << ")\n";
597}
598#endif
599
600//===----------------------------------------------------------------------===//
601
602AnchoredDesc::AnchoredDesc(unsigned T)
603: DebugInfoDesc(T)
604, Anchor(NULL)
605{}
606
607/// ApplyToFields - Target the visitor to the fields of the AnchoredDesc.
608///
609void AnchoredDesc::ApplyToFields(DIVisitor *Visitor) {
610  DebugInfoDesc::ApplyToFields(Visitor);
611
612  Visitor->Apply(Anchor);
613}
614
615//===----------------------------------------------------------------------===//
616
617CompileUnitDesc::CompileUnitDesc()
618: AnchoredDesc(DW_TAG_compile_unit)
619, Language(0)
620, FileName("")
621, Directory("")
622, Producer("")
623{}
624
625// Implement isa/cast/dyncast.
626bool CompileUnitDesc::classof(const DebugInfoDesc *D) {
627  return D->getTag() == DW_TAG_compile_unit;
628}
629
630/// ApplyToFields - Target the visitor to the fields of the CompileUnitDesc.
631///
632void CompileUnitDesc::ApplyToFields(DIVisitor *Visitor) {
633  AnchoredDesc::ApplyToFields(Visitor);
634
635  // Handle cases out of sync with compiler.
636  if (getVersion() == 0) {
637    unsigned DebugVersion;
638    Visitor->Apply(DebugVersion);
639  }
640
641  Visitor->Apply(Language);
642  Visitor->Apply(FileName);
643  Visitor->Apply(Directory);
644  Visitor->Apply(Producer);
645}
646
647/// getDescString - Return a string used to compose global names and labels.
648///
649const char *CompileUnitDesc::getDescString() const {
650  return "llvm.dbg.compile_unit";
651}
652
653/// getTypeString - Return a string used to label this descriptors type.
654///
655const char *CompileUnitDesc::getTypeString() const {
656  return "llvm.dbg.compile_unit.type";
657}
658
659/// getAnchorString - Return a string used to label this descriptor's anchor.
660///
661const char *CompileUnitDesc::AnchorString = "llvm.dbg.compile_units";
662const char *CompileUnitDesc::getAnchorString() const {
663  return AnchorString;
664}
665
666#ifndef NDEBUG
667void CompileUnitDesc::dump() {
668  cerr << getDescString() << " "
669       << "Version(" << getVersion() << "), "
670       << "Tag(" << getTag() << "), "
671       << "Anchor(" << getAnchor() << "), "
672       << "Language(" << Language << "), "
673       << "FileName(\"" << FileName << "\"), "
674       << "Directory(\"" << Directory << "\"), "
675       << "Producer(\"" << Producer << "\")\n";
676}
677#endif
678
679//===----------------------------------------------------------------------===//
680
681TypeDesc::TypeDesc(unsigned T)
682: DebugInfoDesc(T)
683, Context(NULL)
684, Name("")
685, File(NULL)
686, Line(0)
687, Size(0)
688, Align(0)
689, Offset(0)
690, Flags(0)
691{}
692
693/// ApplyToFields - Target the visitor to the fields of the TypeDesc.
694///
695void TypeDesc::ApplyToFields(DIVisitor *Visitor) {
696  DebugInfoDesc::ApplyToFields(Visitor);
697
698  Visitor->Apply(Context);
699  Visitor->Apply(Name);
700  Visitor->Apply(File);
701  Visitor->Apply(Line);
702  Visitor->Apply(Size);
703  Visitor->Apply(Align);
704  Visitor->Apply(Offset);
705  if (getVersion() > LLVMDebugVersion4) Visitor->Apply(Flags);
706}
707
708/// getDescString - Return a string used to compose global names and labels.
709///
710const char *TypeDesc::getDescString() const {
711  return "llvm.dbg.type";
712}
713
714/// getTypeString - Return a string used to label this descriptor's type.
715///
716const char *TypeDesc::getTypeString() const {
717  return "llvm.dbg.type.type";
718}
719
720#ifndef NDEBUG
721void TypeDesc::dump() {
722  cerr << getDescString() << " "
723       << "Version(" << getVersion() << "), "
724       << "Tag(" << getTag() << "), "
725       << "Context(" << Context << "), "
726       << "Name(\"" << Name << "\"), "
727       << "File(" << File << "), "
728       << "Line(" << Line << "), "
729       << "Size(" << Size << "), "
730       << "Align(" << Align << "), "
731       << "Offset(" << Offset << "), "
732       << "Flags(" << Flags << ")\n";
733}
734#endif
735
736//===----------------------------------------------------------------------===//
737
738BasicTypeDesc::BasicTypeDesc()
739: TypeDesc(DW_TAG_base_type)
740, Encoding(0)
741{}
742
743// Implement isa/cast/dyncast.
744bool BasicTypeDesc::classof(const DebugInfoDesc *D) {
745  return D->getTag() == DW_TAG_base_type;
746}
747
748/// ApplyToFields - Target the visitor to the fields of the BasicTypeDesc.
749///
750void BasicTypeDesc::ApplyToFields(DIVisitor *Visitor) {
751  TypeDesc::ApplyToFields(Visitor);
752
753  Visitor->Apply(Encoding);
754}
755
756/// getDescString - Return a string used to compose global names and labels.
757///
758const char *BasicTypeDesc::getDescString() const {
759  return "llvm.dbg.basictype";
760}
761
762/// getTypeString - Return a string used to label this descriptor's type.
763///
764const char *BasicTypeDesc::getTypeString() const {
765  return "llvm.dbg.basictype.type";
766}
767
768#ifndef NDEBUG
769void BasicTypeDesc::dump() {
770  cerr << getDescString() << " "
771       << "Version(" << getVersion() << "), "
772       << "Tag(" << getTag() << "), "
773       << "Context(" << getContext() << "), "
774       << "Name(\"" << getName() << "\"), "
775       << "Size(" << getSize() << "), "
776       << "Encoding(" << Encoding << ")\n";
777}
778#endif
779
780//===----------------------------------------------------------------------===//
781
782DerivedTypeDesc::DerivedTypeDesc(unsigned T)
783: TypeDesc(T)
784, FromType(NULL)
785{}
786
787// Implement isa/cast/dyncast.
788bool DerivedTypeDesc::classof(const DebugInfoDesc *D) {
789  unsigned T =  D->getTag();
790  switch (T) {
791  case DW_TAG_typedef:
792  case DW_TAG_pointer_type:
793  case DW_TAG_reference_type:
794  case DW_TAG_const_type:
795  case DW_TAG_volatile_type:
796  case DW_TAG_restrict_type:
797  case DW_TAG_member:
798  case DW_TAG_inheritance:
799    return true;
800  default: break;
801  }
802  return false;
803}
804
805/// ApplyToFields - Target the visitor to the fields of the DerivedTypeDesc.
806///
807void DerivedTypeDesc::ApplyToFields(DIVisitor *Visitor) {
808  TypeDesc::ApplyToFields(Visitor);
809
810  Visitor->Apply(FromType);
811}
812
813/// getDescString - Return a string used to compose global names and labels.
814///
815const char *DerivedTypeDesc::getDescString() const {
816  return "llvm.dbg.derivedtype";
817}
818
819/// getTypeString - Return a string used to label this descriptor's type.
820///
821const char *DerivedTypeDesc::getTypeString() const {
822  return "llvm.dbg.derivedtype.type";
823}
824
825#ifndef NDEBUG
826void DerivedTypeDesc::dump() {
827  cerr << getDescString() << " "
828       << "Version(" << getVersion() << "), "
829       << "Tag(" << getTag() << "), "
830       << "Context(" << getContext() << "), "
831       << "Name(\"" << getName() << "\"), "
832       << "Size(" << getSize() << "), "
833       << "File(" << getFile() << "), "
834       << "Line(" << getLine() << "), "
835       << "FromType(" << FromType << ")\n";
836}
837#endif
838
839//===----------------------------------------------------------------------===//
840
841CompositeTypeDesc::CompositeTypeDesc(unsigned T)
842: DerivedTypeDesc(T)
843, Elements()
844{}
845
846// Implement isa/cast/dyncast.
847bool CompositeTypeDesc::classof(const DebugInfoDesc *D) {
848  unsigned T =  D->getTag();
849  switch (T) {
850  case DW_TAG_array_type:
851  case DW_TAG_structure_type:
852  case DW_TAG_union_type:
853  case DW_TAG_enumeration_type:
854  case DW_TAG_vector_type:
855  case DW_TAG_subroutine_type:
856    return true;
857  default: break;
858  }
859  return false;
860}
861
862/// ApplyToFields - Target the visitor to the fields of the CompositeTypeDesc.
863///
864void CompositeTypeDesc::ApplyToFields(DIVisitor *Visitor) {
865  DerivedTypeDesc::ApplyToFields(Visitor);
866
867  Visitor->Apply(Elements);
868}
869
870/// getDescString - Return a string used to compose global names and labels.
871///
872const char *CompositeTypeDesc::getDescString() const {
873  return "llvm.dbg.compositetype";
874}
875
876/// getTypeString - Return a string used to label this descriptor's type.
877///
878const char *CompositeTypeDesc::getTypeString() const {
879  return "llvm.dbg.compositetype.type";
880}
881
882#ifndef NDEBUG
883void CompositeTypeDesc::dump() {
884  cerr << getDescString() << " "
885       << "Version(" << getVersion() << "), "
886       << "Tag(" << getTag() << "), "
887       << "Context(" << getContext() << "), "
888       << "Name(\"" << getName() << "\"), "
889       << "Size(" << getSize() << "), "
890       << "File(" << getFile() << "), "
891       << "Line(" << getLine() << "), "
892       << "FromType(" << getFromType() << "), "
893       << "Elements.size(" << Elements.size() << ")\n";
894}
895#endif
896
897//===----------------------------------------------------------------------===//
898
899SubrangeDesc::SubrangeDesc()
900: DebugInfoDesc(DW_TAG_subrange_type)
901, Lo(0)
902, Hi(0)
903{}
904
905// Implement isa/cast/dyncast.
906bool SubrangeDesc::classof(const DebugInfoDesc *D) {
907  return D->getTag() == DW_TAG_subrange_type;
908}
909
910/// ApplyToFields - Target the visitor to the fields of the SubrangeDesc.
911///
912void SubrangeDesc::ApplyToFields(DIVisitor *Visitor) {
913  DebugInfoDesc::ApplyToFields(Visitor);
914
915  Visitor->Apply(Lo);
916  Visitor->Apply(Hi);
917}
918
919/// getDescString - Return a string used to compose global names and labels.
920///
921const char *SubrangeDesc::getDescString() const {
922  return "llvm.dbg.subrange";
923}
924
925/// getTypeString - Return a string used to label this descriptor's type.
926///
927const char *SubrangeDesc::getTypeString() const {
928  return "llvm.dbg.subrange.type";
929}
930
931#ifndef NDEBUG
932void SubrangeDesc::dump() {
933  cerr << getDescString() << " "
934       << "Version(" << getVersion() << "), "
935       << "Tag(" << getTag() << "), "
936       << "Lo(" << Lo << "), "
937       << "Hi(" << Hi << ")\n";
938}
939#endif
940
941//===----------------------------------------------------------------------===//
942
943EnumeratorDesc::EnumeratorDesc()
944: DebugInfoDesc(DW_TAG_enumerator)
945, Name("")
946, Value(0)
947{}
948
949// Implement isa/cast/dyncast.
950bool EnumeratorDesc::classof(const DebugInfoDesc *D) {
951  return D->getTag() == DW_TAG_enumerator;
952}
953
954/// ApplyToFields - Target the visitor to the fields of the EnumeratorDesc.
955///
956void EnumeratorDesc::ApplyToFields(DIVisitor *Visitor) {
957  DebugInfoDesc::ApplyToFields(Visitor);
958
959  Visitor->Apply(Name);
960  Visitor->Apply(Value);
961}
962
963/// getDescString - Return a string used to compose global names and labels.
964///
965const char *EnumeratorDesc::getDescString() const {
966  return "llvm.dbg.enumerator";
967}
968
969/// getTypeString - Return a string used to label this descriptor's type.
970///
971const char *EnumeratorDesc::getTypeString() const {
972  return "llvm.dbg.enumerator.type";
973}
974
975#ifndef NDEBUG
976void EnumeratorDesc::dump() {
977  cerr << getDescString() << " "
978       << "Version(" << getVersion() << "), "
979       << "Tag(" << getTag() << "), "
980       << "Name(" << Name << "), "
981       << "Value(" << Value << ")\n";
982}
983#endif
984
985//===----------------------------------------------------------------------===//
986
987VariableDesc::VariableDesc(unsigned T)
988: DebugInfoDesc(T)
989, Context(NULL)
990, Name("")
991, File(NULL)
992, Line(0)
993, TyDesc(0)
994{}
995
996// Implement isa/cast/dyncast.
997bool VariableDesc::classof(const DebugInfoDesc *D) {
998  unsigned T =  D->getTag();
999  switch (T) {
1000  case DW_TAG_auto_variable:
1001  case DW_TAG_arg_variable:
1002  case DW_TAG_return_variable:
1003    return true;
1004  default: break;
1005  }
1006  return false;
1007}
1008
1009/// ApplyToFields - Target the visitor to the fields of the VariableDesc.
1010///
1011void VariableDesc::ApplyToFields(DIVisitor *Visitor) {
1012  DebugInfoDesc::ApplyToFields(Visitor);
1013
1014  Visitor->Apply(Context);
1015  Visitor->Apply(Name);
1016  Visitor->Apply(File);
1017  Visitor->Apply(Line);
1018  Visitor->Apply(TyDesc);
1019}
1020
1021/// getDescString - Return a string used to compose global names and labels.
1022///
1023const char *VariableDesc::getDescString() const {
1024  return "llvm.dbg.variable";
1025}
1026
1027/// getTypeString - Return a string used to label this descriptor's type.
1028///
1029const char *VariableDesc::getTypeString() const {
1030  return "llvm.dbg.variable.type";
1031}
1032
1033#ifndef NDEBUG
1034void VariableDesc::dump() {
1035  cerr << getDescString() << " "
1036       << "Version(" << getVersion() << "), "
1037       << "Tag(" << getTag() << "), "
1038       << "Context(" << Context << "), "
1039       << "Name(\"" << Name << "\"), "
1040       << "File(" << File << "), "
1041       << "Line(" << Line << "), "
1042       << "TyDesc(" << TyDesc << ")\n";
1043}
1044#endif
1045
1046//===----------------------------------------------------------------------===//
1047
1048GlobalDesc::GlobalDesc(unsigned T)
1049: AnchoredDesc(T)
1050, Context(0)
1051, Name("")
1052, FullName("")
1053, LinkageName("")
1054, File(NULL)
1055, Line(0)
1056, TyDesc(NULL)
1057, IsStatic(false)
1058, IsDefinition(false)
1059{}
1060
1061/// ApplyToFields - Target the visitor to the fields of the global.
1062///
1063void GlobalDesc::ApplyToFields(DIVisitor *Visitor) {
1064  AnchoredDesc::ApplyToFields(Visitor);
1065
1066  Visitor->Apply(Context);
1067  Visitor->Apply(Name);
1068  Visitor->Apply(FullName);
1069  Visitor->Apply(LinkageName);
1070  Visitor->Apply(File);
1071  Visitor->Apply(Line);
1072  Visitor->Apply(TyDesc);
1073  Visitor->Apply(IsStatic);
1074  Visitor->Apply(IsDefinition);
1075}
1076
1077//===----------------------------------------------------------------------===//
1078
1079GlobalVariableDesc::GlobalVariableDesc()
1080: GlobalDesc(DW_TAG_variable)
1081, Global(NULL)
1082{}
1083
1084// Implement isa/cast/dyncast.
1085bool GlobalVariableDesc::classof(const DebugInfoDesc *D) {
1086  return D->getTag() == DW_TAG_variable;
1087}
1088
1089/// ApplyToFields - Target the visitor to the fields of the GlobalVariableDesc.
1090///
1091void GlobalVariableDesc::ApplyToFields(DIVisitor *Visitor) {
1092  GlobalDesc::ApplyToFields(Visitor);
1093
1094  Visitor->Apply(Global);
1095}
1096
1097/// getDescString - Return a string used to compose global names and labels.
1098///
1099const char *GlobalVariableDesc::getDescString() const {
1100  return "llvm.dbg.global_variable";
1101}
1102
1103/// getTypeString - Return a string used to label this descriptors type.
1104///
1105const char *GlobalVariableDesc::getTypeString() const {
1106  return "llvm.dbg.global_variable.type";
1107}
1108
1109/// getAnchorString - Return a string used to label this descriptor's anchor.
1110///
1111const char *GlobalVariableDesc::AnchorString = "llvm.dbg.global_variables";
1112const char *GlobalVariableDesc::getAnchorString() const {
1113  return AnchorString;
1114}
1115
1116#ifndef NDEBUG
1117void GlobalVariableDesc::dump() {
1118  cerr << getDescString() << " "
1119       << "Version(" << getVersion() << "), "
1120       << "Tag(" << getTag() << "), "
1121       << "Anchor(" << getAnchor() << "), "
1122       << "Name(\"" << getName() << "\"), "
1123       << "FullName(\"" << getFullName() << "\"), "
1124       << "LinkageName(\"" << getLinkageName() << "\"), "
1125       << "File(" << getFile() << "),"
1126       << "Line(" << getLine() << "),"
1127       << "Type(" << getType() << "), "
1128       << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1129       << "IsDefinition(" << (isDefinition() ? "true" : "false") << "), "
1130       << "Global(" << Global << ")\n";
1131}
1132#endif
1133
1134//===----------------------------------------------------------------------===//
1135
1136SubprogramDesc::SubprogramDesc()
1137: GlobalDesc(DW_TAG_subprogram)
1138{}
1139
1140// Implement isa/cast/dyncast.
1141bool SubprogramDesc::classof(const DebugInfoDesc *D) {
1142  return D->getTag() == DW_TAG_subprogram;
1143}
1144
1145/// ApplyToFields - Target the visitor to the fields of the
1146/// SubprogramDesc.
1147void SubprogramDesc::ApplyToFields(DIVisitor *Visitor) {
1148  GlobalDesc::ApplyToFields(Visitor);
1149}
1150
1151/// getDescString - Return a string used to compose global names and labels.
1152///
1153const char *SubprogramDesc::getDescString() const {
1154  return "llvm.dbg.subprogram";
1155}
1156
1157/// getTypeString - Return a string used to label this descriptors type.
1158///
1159const char *SubprogramDesc::getTypeString() const {
1160  return "llvm.dbg.subprogram.type";
1161}
1162
1163/// getAnchorString - Return a string used to label this descriptor's anchor.
1164///
1165const char *SubprogramDesc::AnchorString = "llvm.dbg.subprograms";
1166const char *SubprogramDesc::getAnchorString() const {
1167  return AnchorString;
1168}
1169
1170#ifndef NDEBUG
1171void SubprogramDesc::dump() {
1172  cerr << getDescString() << " "
1173       << "Version(" << getVersion() << "), "
1174       << "Tag(" << getTag() << "), "
1175       << "Anchor(" << getAnchor() << "), "
1176       << "Name(\"" << getName() << "\"), "
1177       << "FullName(\"" << getFullName() << "\"), "
1178       << "LinkageName(\"" << getLinkageName() << "\"), "
1179       << "File(" << getFile() << "),"
1180       << "Line(" << getLine() << "),"
1181       << "Type(" << getType() << "), "
1182       << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1183       << "IsDefinition(" << (isDefinition() ? "true" : "false") << ")\n";
1184}
1185#endif
1186
1187//===----------------------------------------------------------------------===//
1188
1189BlockDesc::BlockDesc()
1190: DebugInfoDesc(DW_TAG_lexical_block)
1191, Context(NULL)
1192{}
1193
1194// Implement isa/cast/dyncast.
1195bool BlockDesc::classof(const DebugInfoDesc *D) {
1196  return D->getTag() == DW_TAG_lexical_block;
1197}
1198
1199/// ApplyToFields - Target the visitor to the fields of the BlockDesc.
1200///
1201void BlockDesc::ApplyToFields(DIVisitor *Visitor) {
1202  DebugInfoDesc::ApplyToFields(Visitor);
1203
1204  Visitor->Apply(Context);
1205}
1206
1207/// getDescString - Return a string used to compose global names and labels.
1208///
1209const char *BlockDesc::getDescString() const {
1210  return "llvm.dbg.block";
1211}
1212
1213/// getTypeString - Return a string used to label this descriptors type.
1214///
1215const char *BlockDesc::getTypeString() const {
1216  return "llvm.dbg.block.type";
1217}
1218
1219#ifndef NDEBUG
1220void BlockDesc::dump() {
1221  cerr << getDescString() << " "
1222       << "Version(" << getVersion() << "), "
1223       << "Tag(" << getTag() << "),"
1224       << "Context(" << Context << ")\n";
1225}
1226#endif
1227
1228//===----------------------------------------------------------------------===//
1229
1230DebugInfoDesc *DIDeserializer::Deserialize(Value *V) {
1231  return Deserialize(getGlobalVariable(V));
1232}
1233DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) {
1234  // Handle NULL.
1235  if (!GV) return NULL;
1236
1237  // Check to see if it has been already deserialized.
1238  DebugInfoDesc *&Slot = GlobalDescs[GV];
1239  if (Slot) return Slot;
1240
1241  // Get the Tag from the global.
1242  unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1243
1244  // Create an empty instance of the correct sort.
1245  Slot = DebugInfoDesc::DescFactory(Tag);
1246
1247  // If not a user defined descriptor.
1248  if (Slot) {
1249    // Deserialize the fields.
1250    DIDeserializeVisitor DRAM(*this, GV);
1251    DRAM.ApplyToFields(Slot);
1252  }
1253
1254  return Slot;
1255}
1256
1257//===----------------------------------------------------------------------===//
1258
1259/// getStrPtrType - Return a "sbyte *" type.
1260///
1261const PointerType *DISerializer::getStrPtrType() {
1262  // If not already defined.
1263  if (!StrPtrTy) {
1264    // Construct the pointer to signed bytes.
1265    StrPtrTy = PointerType::get(Type::Int8Ty);
1266  }
1267
1268  return StrPtrTy;
1269}
1270
1271/// getEmptyStructPtrType - Return a "{ }*" type.
1272///
1273const PointerType *DISerializer::getEmptyStructPtrType() {
1274  // If not already defined.
1275  if (!EmptyStructPtrTy) {
1276    // Construct the empty structure type.
1277    const StructType *EmptyStructTy =
1278                                    StructType::get(std::vector<const Type*>());
1279    // Construct the pointer to empty structure type.
1280    EmptyStructPtrTy = PointerType::get(EmptyStructTy);
1281  }
1282
1283  return EmptyStructPtrTy;
1284}
1285
1286/// getTagType - Return the type describing the specified descriptor (via tag.)
1287///
1288const StructType *DISerializer::getTagType(DebugInfoDesc *DD) {
1289  // Attempt to get the previously defined type.
1290  StructType *&Ty = TagTypes[DD->getTag()];
1291
1292  // If not already defined.
1293  if (!Ty) {
1294    // Set up fields vector.
1295    std::vector<const Type*> Fields;
1296    // Get types of fields.
1297    DIGetTypesVisitor GTAM(*this, Fields);
1298    GTAM.ApplyToFields(DD);
1299
1300    // Construct structured type.
1301    Ty = StructType::get(Fields);
1302
1303    // Register type name with module.
1304    M->addTypeName(DD->getTypeString(), Ty);
1305  }
1306
1307  return Ty;
1308}
1309
1310/// getString - Construct the string as constant string global.
1311///
1312Constant *DISerializer::getString(const std::string &String) {
1313  // Check string cache for previous edition.
1314  Constant *&Slot = StringCache[String];
1315  // Return Constant if previously defined.
1316  if (Slot) return Slot;
1317  // If empty string then use a sbyte* null instead.
1318  if (String.empty()) {
1319    Slot = ConstantPointerNull::get(getStrPtrType());
1320  } else {
1321    // Construct string as an llvm constant.
1322    Constant *ConstStr = ConstantArray::get(String);
1323    // Otherwise create and return a new string global.
1324    GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
1325                                               GlobalVariable::InternalLinkage,
1326                                               ConstStr, ".str", M);
1327    StrGV->setSection("llvm.metadata");
1328    // Convert to generic string pointer.
1329    Slot = ConstantExpr::getBitCast(StrGV, getStrPtrType());
1330  }
1331  return Slot;
1332
1333}
1334
1335/// Serialize - Recursively cast the specified descriptor into a GlobalVariable
1336/// so that it can be serialized to a .bc or .ll file.
1337GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) {
1338  // Check if the DebugInfoDesc is already in the map.
1339  GlobalVariable *&Slot = DescGlobals[DD];
1340
1341  // See if DebugInfoDesc exists, if so return prior GlobalVariable.
1342  if (Slot) return Slot;
1343
1344  // Get the type associated with the Tag.
1345  const StructType *Ty = getTagType(DD);
1346
1347  // Create the GlobalVariable early to prevent infinite recursion.
1348  GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(),
1349                                          NULL, DD->getDescString(), M);
1350  GV->setSection("llvm.metadata");
1351
1352  // Insert new GlobalVariable in DescGlobals map.
1353  Slot = GV;
1354
1355  // Set up elements vector
1356  std::vector<Constant*> Elements;
1357  // Add fields.
1358  DISerializeVisitor SRAM(*this, Elements);
1359  SRAM.ApplyToFields(DD);
1360
1361  // Set the globals initializer.
1362  GV->setInitializer(ConstantStruct::get(Ty, Elements));
1363
1364  return GV;
1365}
1366
1367//===----------------------------------------------------------------------===//
1368
1369/// Verify - Return true if the GlobalVariable appears to be a valid
1370/// serialization of a DebugInfoDesc.
1371bool DIVerifier::Verify(Value *V) {
1372  return !V || Verify(getGlobalVariable(V));
1373}
1374bool DIVerifier::Verify(GlobalVariable *GV) {
1375  // NULLs are valid.
1376  if (!GV) return true;
1377
1378  // Check prior validity.
1379  unsigned &ValiditySlot = Validity[GV];
1380
1381  // If visited before then use old state.
1382  if (ValiditySlot) return ValiditySlot == Valid;
1383
1384  // Assume validity for the time being (recursion.)
1385  ValiditySlot = Valid;
1386
1387  // Make sure the global is internal or link once (anchor.)
1388  if (GV->getLinkage() != GlobalValue::InternalLinkage &&
1389      GV->getLinkage() != GlobalValue::LinkOnceLinkage) {
1390    ValiditySlot = Invalid;
1391    return false;
1392  }
1393
1394  // Get the Tag.
1395  unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1396
1397  // Check for user defined descriptors.
1398  if (Tag == DW_TAG_invalid) {
1399    ValiditySlot = Valid;
1400    return true;
1401  }
1402
1403  // Get the Version.
1404  unsigned Version = DebugInfoDesc::VersionFromGlobal(GV);
1405
1406  // Check for version mismatch.
1407  if (Version != LLVMDebugVersion) {
1408    ValiditySlot = Invalid;
1409    return false;
1410  }
1411
1412  // Construct an empty DebugInfoDesc.
1413  DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag);
1414
1415  // Allow for user defined descriptors.
1416  if (!DD) return true;
1417
1418  // Get the initializer constant.
1419  ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer());
1420
1421  // Get the operand count.
1422  unsigned N = CI->getNumOperands();
1423
1424  // Get the field count.
1425  unsigned &CountSlot = Counts[Tag];
1426  if (!CountSlot) {
1427    // Check the operand count to the field count
1428    DICountVisitor CTAM;
1429    CTAM.ApplyToFields(DD);
1430    CountSlot = CTAM.getCount();
1431  }
1432
1433  // Field count must be at most equal operand count.
1434  if (CountSlot >  N) {
1435    delete DD;
1436    ValiditySlot = Invalid;
1437    return false;
1438  }
1439
1440  // Check each field for valid type.
1441  DIVerifyVisitor VRAM(*this, GV);
1442  VRAM.ApplyToFields(DD);
1443
1444  // Release empty DebugInfoDesc.
1445  delete DD;
1446
1447  // If fields are not valid.
1448  if (!VRAM.isValid()) {
1449    ValiditySlot = Invalid;
1450    return false;
1451  }
1452
1453  return true;
1454}
1455
1456//===----------------------------------------------------------------------===//
1457
1458DebugScope::~DebugScope() {
1459  for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1460  for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1461}
1462
1463//===----------------------------------------------------------------------===//
1464
1465MachineModuleInfo::MachineModuleInfo()
1466: ImmutablePass((intptr_t)&ID)
1467, DR()
1468, VR()
1469, CompileUnits()
1470, Directories()
1471, SourceFiles()
1472, Lines()
1473, LabelIDList()
1474, ScopeMap()
1475, RootScope(NULL)
1476, FrameMoves()
1477, LandingPads()
1478, Personalities()
1479{
1480  // Always emit "no personality" info
1481  Personalities.push_back(NULL);
1482}
1483MachineModuleInfo::~MachineModuleInfo() {
1484
1485}
1486
1487/// doInitialization - Initialize the state for a new module.
1488///
1489bool MachineModuleInfo::doInitialization() {
1490  return false;
1491}
1492
1493/// doFinalization - Tear down the state after completion of a module.
1494///
1495bool MachineModuleInfo::doFinalization() {
1496  return false;
1497}
1498
1499/// BeginFunction - Begin gathering function meta information.
1500///
1501void MachineModuleInfo::BeginFunction(MachineFunction *MF) {
1502  // Coming soon.
1503}
1504
1505/// EndFunction - Discard function meta information.
1506///
1507void MachineModuleInfo::EndFunction() {
1508  // Clean up scope information.
1509  if (RootScope) {
1510    delete RootScope;
1511    ScopeMap.clear();
1512    RootScope = NULL;
1513  }
1514
1515  // Clean up line info.
1516  Lines.clear();
1517
1518  // Clean up frame info.
1519  FrameMoves.clear();
1520
1521  // Clean up exception info.
1522  LandingPads.clear();
1523  TypeInfos.clear();
1524  FilterIds.clear();
1525}
1526
1527/// getDescFor - Convert a Value to a debug information descriptor.
1528///
1529// FIXME - use new Value type when available.
1530DebugInfoDesc *MachineModuleInfo::getDescFor(Value *V) {
1531  return DR.Deserialize(V);
1532}
1533
1534/// Verify - Verify that a Value is debug information descriptor.
1535///
1536bool MachineModuleInfo::Verify(Value *V) {
1537  return VR.Verify(V);
1538}
1539
1540/// AnalyzeModule - Scan the module for global debug information.
1541///
1542void MachineModuleInfo::AnalyzeModule(Module &M) {
1543  SetupCompileUnits(M);
1544}
1545
1546/// needsFrameInfo - Returns true if we need to gather callee-saved register
1547/// move info for the frame.
1548bool MachineModuleInfo::needsFrameInfo() const {
1549  return hasDebugInfo() || ExceptionHandling;
1550}
1551
1552/// SetupCompileUnits - Set up the unique vector of compile units.
1553///
1554void MachineModuleInfo::SetupCompileUnits(Module &M) {
1555  std::vector<CompileUnitDesc *>CU = getAnchoredDescriptors<CompileUnitDesc>(M);
1556
1557  for (unsigned i = 0, N = CU.size(); i < N; i++) {
1558    CompileUnits.insert(CU[i]);
1559  }
1560}
1561
1562/// getCompileUnits - Return a vector of debug compile units.
1563///
1564const UniqueVector<CompileUnitDesc *> MachineModuleInfo::getCompileUnits()const{
1565  return CompileUnits;
1566}
1567
1568/// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
1569/// named GlobalVariable.
1570std::vector<GlobalVariable*>
1571MachineModuleInfo::getGlobalVariablesUsing(Module &M,
1572                                           const std::string &RootName) {
1573  return ::getGlobalVariablesUsing(M, RootName);
1574}
1575
1576/// RecordLabel - Records location information and associates it with a
1577/// debug label.  Returns a unique label ID used to generate a label and
1578/// provide correspondence to the source line list.
1579unsigned MachineModuleInfo::RecordLabel(unsigned Line, unsigned Column,
1580                                       unsigned Source) {
1581  unsigned ID = NextLabelID();
1582  Lines.push_back(SourceLineInfo(Line, Column, Source, ID));
1583  return ID;
1584}
1585
1586/// RecordSource - Register a source file with debug info. Returns an source
1587/// ID.
1588unsigned MachineModuleInfo::RecordSource(const std::string &Directory,
1589                                         const std::string &Source) {
1590  unsigned DirectoryID = Directories.insert(Directory);
1591  return SourceFiles.insert(SourceFileInfo(DirectoryID, Source));
1592}
1593unsigned MachineModuleInfo::RecordSource(const CompileUnitDesc *CompileUnit) {
1594  return RecordSource(CompileUnit->getDirectory(),
1595                      CompileUnit->getFileName());
1596}
1597
1598/// RecordRegionStart - Indicate the start of a region.
1599///
1600unsigned MachineModuleInfo::RecordRegionStart(Value *V) {
1601  // FIXME - need to be able to handle split scopes because of bb cloning.
1602  DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1603  DebugScope *Scope = getOrCreateScope(ScopeDesc);
1604  unsigned ID = NextLabelID();
1605  if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1606  return ID;
1607}
1608
1609/// RecordRegionEnd - Indicate the end of a region.
1610///
1611unsigned MachineModuleInfo::RecordRegionEnd(Value *V) {
1612  // FIXME - need to be able to handle split scopes because of bb cloning.
1613  DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1614  DebugScope *Scope = getOrCreateScope(ScopeDesc);
1615  unsigned ID = NextLabelID();
1616  Scope->setEndLabelID(ID);
1617  return ID;
1618}
1619
1620/// RecordVariable - Indicate the declaration of  a local variable.
1621///
1622void MachineModuleInfo::RecordVariable(Value *V, unsigned FrameIndex) {
1623  VariableDesc *VD = cast<VariableDesc>(DR.Deserialize(V));
1624  DebugScope *Scope = getOrCreateScope(VD->getContext());
1625  DebugVariable *DV = new DebugVariable(VD, FrameIndex);
1626  Scope->AddVariable(DV);
1627}
1628
1629/// getOrCreateScope - Returns the scope associated with the given descriptor.
1630///
1631DebugScope *MachineModuleInfo::getOrCreateScope(DebugInfoDesc *ScopeDesc) {
1632  DebugScope *&Slot = ScopeMap[ScopeDesc];
1633  if (!Slot) {
1634    // FIXME - breaks down when the context is an inlined function.
1635    DebugInfoDesc *ParentDesc = NULL;
1636    if (BlockDesc *Block = dyn_cast<BlockDesc>(ScopeDesc)) {
1637      ParentDesc = Block->getContext();
1638    }
1639    DebugScope *Parent = ParentDesc ? getOrCreateScope(ParentDesc) : NULL;
1640    Slot = new DebugScope(Parent, ScopeDesc);
1641    if (Parent) {
1642      Parent->AddScope(Slot);
1643    } else if (RootScope) {
1644      // FIXME - Add inlined function scopes to the root so we can delete
1645      // them later.  Long term, handle inlined functions properly.
1646      RootScope->AddScope(Slot);
1647    } else {
1648      // First function is top level function.
1649      RootScope = Slot;
1650    }
1651  }
1652  return Slot;
1653}
1654
1655//===-EH-------------------------------------------------------------------===//
1656
1657/// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
1658/// specified MachineBasicBlock.
1659LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
1660    (MachineBasicBlock *LandingPad) {
1661  unsigned N = LandingPads.size();
1662  for (unsigned i = 0; i < N; ++i) {
1663    LandingPadInfo &LP = LandingPads[i];
1664    if (LP.LandingPadBlock == LandingPad)
1665      return LP;
1666  }
1667
1668  LandingPads.push_back(LandingPadInfo(LandingPad));
1669  return LandingPads[N];
1670}
1671
1672/// addInvoke - Provide the begin and end labels of an invoke style call and
1673/// associate it with a try landing pad block.
1674void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
1675                                  unsigned BeginLabel, unsigned EndLabel) {
1676  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1677  LP.BeginLabels.push_back(BeginLabel);
1678  LP.EndLabels.push_back(EndLabel);
1679}
1680
1681/// addLandingPad - Provide the label of a try LandingPad block.
1682///
1683unsigned MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
1684  unsigned LandingPadLabel = NextLabelID();
1685  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1686  LP.LandingPadLabel = LandingPadLabel;
1687  return LandingPadLabel;
1688}
1689
1690/// addPersonality - Provide the personality function for the exception
1691/// information.
1692void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,
1693                                       Function *Personality) {
1694  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1695  LP.Personality = Personality;
1696
1697  for (unsigned i = 0; i < Personalities.size(); ++i)
1698    if (Personalities[i] == Personality)
1699      return;
1700
1701  Personalities.push_back(Personality);
1702}
1703
1704/// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
1705///
1706void MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad,
1707                                        std::vector<GlobalVariable *> &TyInfo) {
1708  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1709  for (unsigned N = TyInfo.size(); N; --N)
1710    LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
1711}
1712
1713/// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
1714///
1715void MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad,
1716                                        std::vector<GlobalVariable *> &TyInfo) {
1717  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1718  std::vector<unsigned> IdsInFilter (TyInfo.size());
1719  for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
1720    IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
1721  LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
1722}
1723
1724/// TidyLandingPads - Remap landing pad labels and remove any deleted landing
1725/// pads.
1726void MachineModuleInfo::TidyLandingPads() {
1727  for (unsigned i = 0; i != LandingPads.size(); ) {
1728    LandingPadInfo &LandingPad = LandingPads[i];
1729    LandingPad.LandingPadLabel = MappedLabel(LandingPad.LandingPadLabel);
1730
1731    // Special case: we *should* emit LPs with null LP MBB. This indicates
1732    // "rethrow" case.
1733    if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
1734      LandingPads.erase(LandingPads.begin() + i);
1735      continue;
1736    }
1737
1738    for (unsigned j=0; j != LandingPads[i].BeginLabels.size(); ) {
1739      unsigned BeginLabel = MappedLabel(LandingPad.BeginLabels[j]);
1740      unsigned EndLabel = MappedLabel(LandingPad.EndLabels[j]);
1741
1742
1743      if (!BeginLabel || !EndLabel) {
1744        LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
1745        LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
1746        continue;
1747      }
1748
1749      LandingPad.BeginLabels[j] = BeginLabel;
1750      LandingPad.EndLabels[j] = EndLabel;
1751      ++j;
1752    }
1753
1754    ++i;
1755  }
1756}
1757
1758/// getTypeIDFor - Return the type id for the specified typeinfo.  This is
1759/// function wide.
1760unsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {
1761  for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
1762    if (TypeInfos[i] == TI) return i + 1;
1763
1764  TypeInfos.push_back(TI);
1765  return TypeInfos.size();
1766}
1767
1768/// getFilterIDFor - Return the filter id for the specified typeinfos.  This is
1769/// function wide.
1770int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
1771  // TODO: map duplicate filters to the same filter id; a filter equal to the
1772  // tail of an existing filter also need not be added; re-order filters and
1773  // filter elements to maximize this kind of sharing.
1774  int FilterID = -(1 + FilterIds.size());
1775  FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
1776  for (unsigned I = 0, N = TyIds.size(); I != N; ++I)
1777    FilterIds.push_back(TyIds[I]);
1778  FilterIds.push_back(0); // terminator
1779  return FilterID;
1780}
1781
1782/// getPersonality - Return the personality function for the current function.
1783Function *MachineModuleInfo::getPersonality() const {
1784  // FIXME: Until PR1414 will be fixed, we're using 1 personality function per
1785  // function
1786  return !LandingPads.empty() ? LandingPads[0].Personality : NULL;
1787}
1788
1789/// getPersonalityIndex - Return unique index for current personality
1790/// function. NULL personality function should always get zero index.
1791unsigned MachineModuleInfo::getPersonalityIndex() const {
1792  const Function* Personality = NULL;
1793
1794  // Scan landing pads. If there is at least one non-NULL personality - use it.
1795  for (unsigned i = 0; i != LandingPads.size(); ++i)
1796    if (LandingPads[i].Personality) {
1797      Personality = LandingPads[i].Personality;
1798      break;
1799    }
1800
1801  for (unsigned i = 0; i < Personalities.size(); ++i) {
1802    if (Personalities[i] == Personality)
1803      return i;
1804  }
1805
1806  // This should never happen
1807  assert(0 && "Personality function should be set!");
1808  return 0;
1809}
1810
1811//===----------------------------------------------------------------------===//
1812/// DebugLabelFolding pass - This pass prunes out redundant labels.  This allows
1813/// a info consumer to determine if the range of two labels is empty, by seeing
1814/// if the labels map to the same reduced label.
1815
1816namespace llvm {
1817
1818struct DebugLabelFolder : public MachineFunctionPass {
1819  static char ID;
1820  DebugLabelFolder() : MachineFunctionPass((intptr_t)&ID) {}
1821
1822  virtual bool runOnMachineFunction(MachineFunction &MF);
1823  virtual const char *getPassName() const { return "Label Folder"; }
1824};
1825
1826char DebugLabelFolder::ID = 0;
1827
1828bool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) {
1829  // Get machine module info.
1830  MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>();
1831  if (!MMI) return false;
1832  // Get target instruction info.
1833  const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
1834  if (!TII) return false;
1835
1836  // Track if change is made.
1837  bool MadeChange = false;
1838  // No prior label to begin.
1839  unsigned PriorLabel = 0;
1840
1841  // Iterate through basic blocks.
1842  for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
1843       BB != E; ++BB) {
1844    // Iterate through instructions.
1845    for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1846      // Is it a label.
1847      if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
1848        // The label ID # is always operand #0, an immediate.
1849        unsigned NextLabel = I->getOperand(0).getImm();
1850
1851        // If there was an immediate prior label.
1852        if (PriorLabel) {
1853          // Remap the current label to prior label.
1854          MMI->RemapLabel(NextLabel, PriorLabel);
1855          // Delete the current label.
1856          I = BB->erase(I);
1857          // Indicate a change has been made.
1858          MadeChange = true;
1859          continue;
1860        } else {
1861          // Start a new round.
1862          PriorLabel = NextLabel;
1863        }
1864       } else {
1865        // No consecutive labels.
1866        PriorLabel = 0;
1867      }
1868
1869      ++I;
1870    }
1871  }
1872
1873  return MadeChange;
1874}
1875
1876FunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); }
1877
1878}
1879
1880