1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/CodeGen/MachineModuleInfo.h"
12 #include "llvm/Constants.h"
13 #include "llvm/Analysis/ValueTracking.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineLocation.h"
17 #include "llvm/CodeGen/MachineDebugInfoDesc.h"
18 #include "llvm/Target/TargetInstrInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetOptions.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Module.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/Streams.h"
29 using namespace llvm::dwarf;
31 // Handle the Pass registration stuff necessary to use TargetData's.
32 static RegisterPass<MachineModuleInfo>
33 X("machinemoduleinfo", "Module Information");
34 char MachineModuleInfo::ID = 0;
36 //===----------------------------------------------------------------------===//
38 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
39 /// specified value in their initializer somewhere.
41 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
42 // Scan though value users.
43 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
44 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
45 // If the user is a GlobalVariable then add to result.
47 } else if (Constant *C = dyn_cast<Constant>(*I)) {
48 // If the user is a constant variable then scan its users
49 getGlobalVariablesUsing(C, Result);
54 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
55 /// named GlobalVariable.
57 getGlobalVariablesUsing(Module &M, const std::string &RootName,
58 std::vector<GlobalVariable*> &Result) {
59 std::vector<const Type*> FieldTypes;
60 FieldTypes.push_back(Type::Int32Ty);
61 FieldTypes.push_back(Type::Int32Ty);
63 // Get the GlobalVariable root.
64 GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
65 StructType::get(FieldTypes));
67 // If present and linkonce then scan for users.
68 if (UseRoot && UseRoot->hasLinkOnceLinkage())
69 getGlobalVariablesUsing(UseRoot, Result);
72 /// isStringValue - Return true if the given value can be coerced to a string.
74 static bool isStringValue(Value *V) {
75 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
76 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
77 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
78 return Init->isString();
80 } else if (Constant *C = dyn_cast<Constant>(V)) {
81 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
82 return isStringValue(GV);
83 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
84 if (CE->getOpcode() == Instruction::GetElementPtr) {
85 if (CE->getNumOperands() == 3 &&
86 cast<Constant>(CE->getOperand(1))->isNullValue() &&
87 isa<ConstantInt>(CE->getOperand(2))) {
88 return isStringValue(CE->getOperand(0));
96 /// getGlobalVariable - Return either a direct or cast Global value.
98 static GlobalVariable *getGlobalVariable(Value *V) {
99 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
101 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
102 if (CE->getOpcode() == Instruction::BitCast) {
103 return dyn_cast<GlobalVariable>(CE->getOperand(0));
104 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
105 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
106 if (!CE->getOperand(i)->isNullValue())
109 return dyn_cast<GlobalVariable>(CE->getOperand(0));
115 /// isGlobalVariable - Return true if the given value can be coerced to a
117 static bool isGlobalVariable(Value *V) {
118 if (isa<GlobalVariable>(V) || isa<ConstantPointerNull>(V)) {
120 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
121 if (CE->getOpcode() == Instruction::BitCast) {
122 return isa<GlobalVariable>(CE->getOperand(0));
123 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
124 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
125 if (!CE->getOperand(i)->isNullValue())
128 return isa<GlobalVariable>(CE->getOperand(0));
134 //===----------------------------------------------------------------------===//
136 /// ApplyToFields - Target the visitor to each field of the debug information
138 void DIVisitor::ApplyToFields(DebugInfoDesc *DD) {
139 DD->ApplyToFields(this);
144 //===----------------------------------------------------------------------===//
145 /// DICountVisitor - This DIVisitor counts all the fields in the supplied debug
146 /// the supplied DebugInfoDesc.
147 class DICountVisitor : public DIVisitor {
149 unsigned Count; // Running count of fields.
152 DICountVisitor() : DIVisitor(), Count(0) {}
155 unsigned getCount() const { return Count; }
157 /// Apply - Count each of the fields.
159 virtual void Apply(int &Field) { ++Count; }
160 virtual void Apply(unsigned &Field) { ++Count; }
161 virtual void Apply(int64_t &Field) { ++Count; }
162 virtual void Apply(uint64_t &Field) { ++Count; }
163 virtual void Apply(bool &Field) { ++Count; }
164 virtual void Apply(std::string &Field) { ++Count; }
165 virtual void Apply(DebugInfoDesc *&Field) { ++Count; }
166 virtual void Apply(GlobalVariable *&Field) { ++Count; }
167 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
172 //===----------------------------------------------------------------------===//
173 /// DIDeserializeVisitor - This DIVisitor deserializes all the fields in the
174 /// supplied DebugInfoDesc.
175 class DIDeserializeVisitor : public DIVisitor {
177 DIDeserializer &DR; // Active deserializer.
178 unsigned I; // Current operand index.
179 ConstantStruct *CI; // GlobalVariable constant initializer.
182 DIDeserializeVisitor(DIDeserializer &D, GlobalVariable *GV)
183 : DIVisitor(), DR(D), I(0), CI(cast<ConstantStruct>(GV->getInitializer()))
186 /// Apply - Set the value of each of the fields.
188 virtual void Apply(int &Field) {
189 Constant *C = CI->getOperand(I++);
190 Field = cast<ConstantInt>(C)->getSExtValue();
192 virtual void Apply(unsigned &Field) {
193 Constant *C = CI->getOperand(I++);
194 Field = cast<ConstantInt>(C)->getZExtValue();
196 virtual void Apply(int64_t &Field) {
197 Constant *C = CI->getOperand(I++);
198 Field = cast<ConstantInt>(C)->getSExtValue();
200 virtual void Apply(uint64_t &Field) {
201 Constant *C = CI->getOperand(I++);
202 Field = cast<ConstantInt>(C)->getZExtValue();
204 virtual void Apply(bool &Field) {
205 Constant *C = CI->getOperand(I++);
206 Field = cast<ConstantInt>(C)->getZExtValue();
208 virtual void Apply(std::string &Field) {
209 Constant *C = CI->getOperand(I++);
210 // Fills in the string if it succeeds
211 if (!GetConstantStringInfo(C, Field))
214 virtual void Apply(DebugInfoDesc *&Field) {
215 Constant *C = CI->getOperand(I++);
216 Field = DR.Deserialize(C);
218 virtual void Apply(GlobalVariable *&Field) {
219 Constant *C = CI->getOperand(I++);
220 Field = getGlobalVariable(C);
222 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
224 Constant *C = CI->getOperand(I++);
225 GlobalVariable *GV = getGlobalVariable(C);
226 if (GV->hasInitializer()) {
227 if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
228 for (unsigned i = 0, N = CA->getNumOperands(); i < N; ++i) {
229 GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
230 DebugInfoDesc *DE = DR.Deserialize(GVE);
233 } else if (GV->getInitializer()->isNullValue()) {
234 if (const ArrayType *T =
235 dyn_cast<ArrayType>(GV->getType()->getElementType())) {
236 Field.resize(T->getNumElements());
243 //===----------------------------------------------------------------------===//
244 /// DISerializeVisitor - This DIVisitor serializes all the fields in
245 /// the supplied DebugInfoDesc.
246 class DISerializeVisitor : public DIVisitor {
248 DISerializer &SR; // Active serializer.
249 std::vector<Constant*> &Elements; // Element accumulator.
252 DISerializeVisitor(DISerializer &S, std::vector<Constant*> &E)
258 /// Apply - Set the value of each of the fields.
260 virtual void Apply(int &Field) {
261 Elements.push_back(ConstantInt::get(Type::Int32Ty, int32_t(Field)));
263 virtual void Apply(unsigned &Field) {
264 Elements.push_back(ConstantInt::get(Type::Int32Ty, uint32_t(Field)));
266 virtual void Apply(int64_t &Field) {
267 Elements.push_back(ConstantInt::get(Type::Int64Ty, int64_t(Field)));
269 virtual void Apply(uint64_t &Field) {
270 Elements.push_back(ConstantInt::get(Type::Int64Ty, uint64_t(Field)));
272 virtual void Apply(bool &Field) {
273 Elements.push_back(ConstantInt::get(Type::Int1Ty, Field));
275 virtual void Apply(std::string &Field) {
276 Elements.push_back(SR.getString(Field));
278 virtual void Apply(DebugInfoDesc *&Field) {
279 GlobalVariable *GV = NULL;
281 // If non-NULL then convert to global.
282 if (Field) GV = SR.Serialize(Field);
284 // FIXME - At some point should use specific type.
285 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
288 // Set to pointer to global.
289 Elements.push_back(ConstantExpr::getBitCast(GV, EmptyTy));
292 Elements.push_back(ConstantPointerNull::get(EmptyTy));
295 virtual void Apply(GlobalVariable *&Field) {
296 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
298 Elements.push_back(ConstantExpr::getBitCast(Field, EmptyTy));
300 Elements.push_back(ConstantPointerNull::get(EmptyTy));
303 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
304 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
305 unsigned N = Field.size();
306 ArrayType *AT = ArrayType::get(EmptyTy, N);
307 std::vector<Constant *> ArrayElements;
309 for (unsigned i = 0, N = Field.size(); i < N; ++i) {
310 if (DebugInfoDesc *Element = Field[i]) {
311 GlobalVariable *GVE = SR.Serialize(Element);
312 Constant *CE = ConstantExpr::getBitCast(GVE, EmptyTy);
313 ArrayElements.push_back(cast<Constant>(CE));
315 ArrayElements.push_back(ConstantPointerNull::get(EmptyTy));
319 Constant *CA = ConstantArray::get(AT, ArrayElements);
320 GlobalVariable *CAGV = new GlobalVariable(AT, true,
321 GlobalValue::InternalLinkage,
322 CA, "llvm.dbg.array",
324 CAGV->setSection("llvm.metadata");
325 Constant *CAE = ConstantExpr::getBitCast(CAGV, EmptyTy);
326 Elements.push_back(CAE);
330 //===----------------------------------------------------------------------===//
331 /// DIGetTypesVisitor - This DIVisitor gathers all the field types in
332 /// the supplied DebugInfoDesc.
333 class DIGetTypesVisitor : public DIVisitor {
335 DISerializer &SR; // Active serializer.
336 std::vector<const Type*> &Fields; // Type accumulator.
339 DIGetTypesVisitor(DISerializer &S, std::vector<const Type*> &F)
345 /// Apply - Set the value of each of the fields.
347 virtual void Apply(int &Field) {
348 Fields.push_back(Type::Int32Ty);
350 virtual void Apply(unsigned &Field) {
351 Fields.push_back(Type::Int32Ty);
353 virtual void Apply(int64_t &Field) {
354 Fields.push_back(Type::Int64Ty);
356 virtual void Apply(uint64_t &Field) {
357 Fields.push_back(Type::Int64Ty);
359 virtual void Apply(bool &Field) {
360 Fields.push_back(Type::Int1Ty);
362 virtual void Apply(std::string &Field) {
363 Fields.push_back(SR.getStrPtrType());
365 virtual void Apply(DebugInfoDesc *&Field) {
366 // FIXME - At some point should use specific type.
367 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
368 Fields.push_back(EmptyTy);
370 virtual void Apply(GlobalVariable *&Field) {
371 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
372 Fields.push_back(EmptyTy);
374 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
375 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
376 Fields.push_back(EmptyTy);
380 //===----------------------------------------------------------------------===//
381 /// DIVerifyVisitor - This DIVisitor verifies all the field types against
382 /// a constant initializer.
383 class DIVerifyVisitor : public DIVisitor {
385 DIVerifier &VR; // Active verifier.
386 bool IsValid; // Validity status.
387 unsigned I; // Current operand index.
388 ConstantStruct *CI; // GlobalVariable constant initializer.
391 DIVerifyVisitor(DIVerifier &V, GlobalVariable *GV)
396 , CI(cast<ConstantStruct>(GV->getInitializer()))
401 bool isValid() const { return IsValid; }
403 /// Apply - Set the value of each of the fields.
405 virtual void Apply(int &Field) {
406 Constant *C = CI->getOperand(I++);
407 IsValid = IsValid && isa<ConstantInt>(C);
409 virtual void Apply(unsigned &Field) {
410 Constant *C = CI->getOperand(I++);
411 IsValid = IsValid && isa<ConstantInt>(C);
413 virtual void Apply(int64_t &Field) {
414 Constant *C = CI->getOperand(I++);
415 IsValid = IsValid && isa<ConstantInt>(C);
417 virtual void Apply(uint64_t &Field) {
418 Constant *C = CI->getOperand(I++);
419 IsValid = IsValid && isa<ConstantInt>(C);
421 virtual void Apply(bool &Field) {
422 Constant *C = CI->getOperand(I++);
423 IsValid = IsValid && isa<ConstantInt>(C) && C->getType() == Type::Int1Ty;
425 virtual void Apply(std::string &Field) {
426 Constant *C = CI->getOperand(I++);
428 (!C || isStringValue(C) || C->isNullValue());
430 virtual void Apply(DebugInfoDesc *&Field) {
431 // FIXME - Prepare the correct descriptor.
432 Constant *C = CI->getOperand(I++);
433 IsValid = IsValid && isGlobalVariable(C);
435 virtual void Apply(GlobalVariable *&Field) {
436 Constant *C = CI->getOperand(I++);
437 IsValid = IsValid && isGlobalVariable(C);
439 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
440 Constant *C = CI->getOperand(I++);
441 IsValid = IsValid && isGlobalVariable(C);
442 if (!IsValid) return;
444 GlobalVariable *GV = getGlobalVariable(C);
445 IsValid = IsValid && GV && GV->hasInitializer();
446 if (!IsValid) return;
448 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
449 IsValid = IsValid && CA;
450 if (!IsValid) return;
452 for (unsigned i = 0, N = CA->getNumOperands(); IsValid && i < N; ++i) {
453 IsValid = IsValid && isGlobalVariable(CA->getOperand(i));
454 if (!IsValid) return;
456 GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
464 //===----------------------------------------------------------------------===//
466 DebugInfoDesc *DIDeserializer::Deserialize(Value *V) {
467 return Deserialize(getGlobalVariable(V));
469 DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) {
471 if (!GV) return NULL;
473 // Check to see if it has been already deserialized.
474 DebugInfoDesc *&Slot = GlobalDescs[GV];
475 if (Slot) return Slot;
477 // Get the Tag from the global.
478 unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
480 // Create an empty instance of the correct sort.
481 Slot = DebugInfoDesc::DescFactory(Tag);
483 // If not a user defined descriptor.
485 // Deserialize the fields.
486 DIDeserializeVisitor DRAM(*this, GV);
487 DRAM.ApplyToFields(Slot);
493 //===----------------------------------------------------------------------===//
495 /// getStrPtrType - Return a "sbyte *" type.
497 const PointerType *DISerializer::getStrPtrType() {
498 // If not already defined.
500 // Construct the pointer to signed bytes.
501 StrPtrTy = PointerType::getUnqual(Type::Int8Ty);
507 /// getEmptyStructPtrType - Return a "{ }*" type.
509 const PointerType *DISerializer::getEmptyStructPtrType() {
510 // If not already defined.
511 if (EmptyStructPtrTy) return EmptyStructPtrTy;
513 // Construct the pointer to empty structure type.
514 const StructType *EmptyStructTy =
515 StructType::get(std::vector<const Type*>());
517 // Construct the pointer to empty structure type.
518 EmptyStructPtrTy = PointerType::getUnqual(EmptyStructTy);
519 return EmptyStructPtrTy;
522 /// getTagType - Return the type describing the specified descriptor (via tag.)
524 const StructType *DISerializer::getTagType(DebugInfoDesc *DD) {
525 // Attempt to get the previously defined type.
526 StructType *&Ty = TagTypes[DD->getTag()];
528 // If not already defined.
530 // Set up fields vector.
531 std::vector<const Type*> Fields;
532 // Get types of fields.
533 DIGetTypesVisitor GTAM(*this, Fields);
534 GTAM.ApplyToFields(DD);
536 // Construct structured type.
537 Ty = StructType::get(Fields);
539 // Register type name with module.
540 M->addTypeName(DD->getTypeString(), Ty);
546 /// getString - Construct the string as constant string global.
548 Constant *DISerializer::getString(const std::string &String) {
549 // Check string cache for previous edition.
550 Constant *&Slot = StringCache[String.c_str()];
552 // Return Constant if previously defined.
553 if (Slot) return Slot;
555 // If empty string then use a sbyte* null instead.
556 if (String.empty()) {
557 Slot = ConstantPointerNull::get(getStrPtrType());
559 // Construct string as an llvm constant.
560 Constant *ConstStr = ConstantArray::get(String);
562 // Otherwise create and return a new string global.
563 GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
564 GlobalVariable::InternalLinkage,
565 ConstStr, ".str", M);
566 StrGV->setSection("llvm.metadata");
568 // Convert to generic string pointer.
569 Slot = ConstantExpr::getBitCast(StrGV, getStrPtrType());
576 /// Serialize - Recursively cast the specified descriptor into a GlobalVariable
577 /// so that it can be serialized to a .bc or .ll file.
578 GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) {
579 // Check if the DebugInfoDesc is already in the map.
580 GlobalVariable *&Slot = DescGlobals[DD];
582 // See if DebugInfoDesc exists, if so return prior GlobalVariable.
583 if (Slot) return Slot;
585 // Get the type associated with the Tag.
586 const StructType *Ty = getTagType(DD);
588 // Create the GlobalVariable early to prevent infinite recursion.
589 GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(),
590 NULL, DD->getDescString(), M);
591 GV->setSection("llvm.metadata");
593 // Insert new GlobalVariable in DescGlobals map.
596 // Set up elements vector
597 std::vector<Constant*> Elements;
599 DISerializeVisitor SRAM(*this, Elements);
600 SRAM.ApplyToFields(DD);
602 // Set the globals initializer.
603 GV->setInitializer(ConstantStruct::get(Ty, Elements));
608 /// addDescriptor - Directly connect DD with existing GV.
609 void DISerializer::addDescriptor(DebugInfoDesc *DD,
610 GlobalVariable *GV) {
611 DescGlobals[DD] = GV;
614 //===----------------------------------------------------------------------===//
616 /// Verify - Return true if the GlobalVariable appears to be a valid
617 /// serialization of a DebugInfoDesc.
618 bool DIVerifier::Verify(Value *V) {
619 return !V || Verify(getGlobalVariable(V));
621 bool DIVerifier::Verify(GlobalVariable *GV) {
623 if (!GV) return true;
625 // Check prior validity.
626 unsigned &ValiditySlot = Validity[GV];
628 // If visited before then use old state.
629 if (ValiditySlot) return ValiditySlot == Valid;
631 // Assume validity for the time being (recursion.)
632 ValiditySlot = Valid;
634 // Make sure the global is internal or link once (anchor.)
635 if (GV->getLinkage() != GlobalValue::InternalLinkage &&
636 GV->getLinkage() != GlobalValue::LinkOnceLinkage) {
637 ValiditySlot = Invalid;
642 unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
644 // Check for user defined descriptors.
645 if (Tag == DW_TAG_invalid) {
646 ValiditySlot = Valid;
651 unsigned Version = DebugInfoDesc::VersionFromGlobal(GV);
653 // Check for version mismatch.
654 if (Version != LLVMDebugVersion) {
655 ValiditySlot = Invalid;
659 // Construct an empty DebugInfoDesc.
660 DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag);
662 // Allow for user defined descriptors.
663 if (!DD) return true;
665 // Get the initializer constant.
666 ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer());
668 // Get the operand count.
669 unsigned N = CI->getNumOperands();
671 // Get the field count.
672 unsigned &CountSlot = Counts[Tag];
674 // Check the operand count to the field count
676 CTAM.ApplyToFields(DD);
677 CountSlot = CTAM.getCount();
680 // Field count must be at most equal operand count.
683 ValiditySlot = Invalid;
687 // Check each field for valid type.
688 DIVerifyVisitor VRAM(*this, GV);
689 VRAM.ApplyToFields(DD);
691 // Release empty DebugInfoDesc.
694 // If fields are not valid.
695 if (!VRAM.isValid()) {
696 ValiditySlot = Invalid;
703 /// isVerified - Return true if the specified GV has already been
704 /// verified as a debug information descriptor.
705 bool DIVerifier::isVerified(GlobalVariable *GV) {
706 unsigned &ValiditySlot = Validity[GV];
707 if (ValiditySlot) return ValiditySlot == Valid;
711 //===----------------------------------------------------------------------===//
713 DebugScope::~DebugScope() {
714 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
715 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
718 //===----------------------------------------------------------------------===//
720 MachineModuleInfo::MachineModuleInfo()
721 : ImmutablePass((intptr_t)&ID)
737 // Always emit "no personality" info
738 Personalities.push_back(NULL);
740 MachineModuleInfo::~MachineModuleInfo() {
744 /// doInitialization - Initialize the state for a new module.
746 bool MachineModuleInfo::doInitialization() {
750 /// doFinalization - Tear down the state after completion of a module.
752 bool MachineModuleInfo::doFinalization() {
756 /// BeginFunction - Begin gathering function meta information.
758 void MachineModuleInfo::BeginFunction(MachineFunction *MF) {
762 /// EndFunction - Discard function meta information.
764 void MachineModuleInfo::EndFunction() {
765 // Clean up scope information.
772 // Clean up line info.
775 // Clean up frame info.
778 // Clean up exception info.
787 /// getDescFor - Convert a Value to a debug information descriptor.
789 // FIXME - use new Value type when available.
790 DebugInfoDesc *MachineModuleInfo::getDescFor(Value *V) {
791 return DR.Deserialize(V);
794 /// AnalyzeModule - Scan the module for global debug information.
796 void MachineModuleInfo::AnalyzeModule(Module &M) {
797 SetupCompileUnits(M);
799 // Insert functions in the llvm.used array into UsedFunctions.
800 GlobalVariable *GV = M.getGlobalVariable("llvm.used");
801 if (!GV || !GV->hasInitializer()) return;
803 // Should be an array of 'i8*'.
804 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
805 if (InitList == 0) return;
807 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
808 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InitList->getOperand(i)))
809 if (CE->getOpcode() == Instruction::BitCast)
810 if (Function *F = dyn_cast<Function>(CE->getOperand(0)))
811 UsedFunctions.insert(F);
815 /// SetupCompileUnits - Set up the unique vector of compile units.
817 void MachineModuleInfo::SetupCompileUnits(Module &M) {
818 std::vector<void*> CUList;
820 getAnchoredDescriptors(M, &CUD, CUList);
822 for (unsigned i = 0, N = CUList.size(); i < N; i++)
823 CompileUnits.insert((CompileUnitDesc*)CUList[i]);
826 /// getCompileUnits - Return a vector of debug compile units.
828 const UniqueVector<CompileUnitDesc *> MachineModuleInfo::getCompileUnits()const{
832 /// getAnchoredDescriptors - Return a vector of anchored debug descriptors.
835 MachineModuleInfo::getAnchoredDescriptors(Module &M, const AnchoredDesc *Desc,
836 std::vector<void*> &AnchoredDescs) {
837 std::vector<GlobalVariable*> Globals;
838 getGlobalVariablesUsing(M, Desc->getAnchorString(), Globals);
840 for (unsigned i = 0, N = Globals.size(); i < N; ++i) {
841 GlobalVariable *GV = Globals[i];
843 // FIXME - In the short term, changes are too drastic to continue.
844 if (DebugInfoDesc::TagFromGlobal(GV) == Desc->getTag() &&
845 DebugInfoDesc::VersionFromGlobal(GV) == LLVMDebugVersion)
846 AnchoredDescs.push_back(DR.Deserialize(GV));
850 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
851 /// named GlobalVariable.
853 MachineModuleInfo::getGlobalVariablesUsing(Module &M,
854 const std::string &RootName,
855 std::vector<GlobalVariable*> &Globals) {
856 return ::getGlobalVariablesUsing(M, RootName, Globals);
859 /// RecordSourceLine - Records location information and associates it with a
860 /// debug label. Returns a unique label ID used to generate a label and
861 /// provide correspondence to the source line list.
862 unsigned MachineModuleInfo::RecordSourceLine(unsigned Line, unsigned Column,
864 unsigned ID = NextLabelID();
865 Lines.push_back(SourceLineInfo(Line, Column, Source, ID));
869 /// RecordSource - Register a source file with debug info. Returns an source
871 unsigned MachineModuleInfo::RecordSource(const std::string &Directory,
872 const std::string &Source) {
873 unsigned DirectoryID = Directories.insert(Directory);
874 return SourceFiles.insert(SourceFileInfo(DirectoryID, Source));
876 unsigned MachineModuleInfo::RecordSource(const CompileUnitDesc *CompileUnit) {
877 return RecordSource(CompileUnit->getDirectory(),
878 CompileUnit->getFileName());
881 /// RecordRegionStart - Indicate the start of a region.
883 unsigned MachineModuleInfo::RecordRegionStart(Value *V) {
884 // FIXME - need to be able to handle split scopes because of bb cloning.
885 DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
886 DebugScope *Scope = getOrCreateScope(ScopeDesc);
887 unsigned ID = NextLabelID();
888 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
892 /// RecordRegionEnd - Indicate the end of a region.
894 unsigned MachineModuleInfo::RecordRegionEnd(Value *V) {
895 // FIXME - need to be able to handle split scopes because of bb cloning.
896 DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
897 DebugScope *Scope = getOrCreateScope(ScopeDesc);
898 unsigned ID = NextLabelID();
899 Scope->setEndLabelID(ID);
903 /// RecordVariable - Indicate the declaration of a local variable.
905 void MachineModuleInfo::RecordVariable(GlobalValue *GV, unsigned FrameIndex) {
906 VariableDesc *VD = cast<VariableDesc>(DR.Deserialize(GV));
907 DebugScope *Scope = getOrCreateScope(VD->getContext());
908 DebugVariable *DV = new DebugVariable(VD, FrameIndex);
909 Scope->AddVariable(DV);
912 /// getOrCreateScope - Returns the scope associated with the given descriptor.
914 DebugScope *MachineModuleInfo::getOrCreateScope(DebugInfoDesc *ScopeDesc) {
915 DebugScope *&Slot = ScopeMap[ScopeDesc];
917 // FIXME - breaks down when the context is an inlined function.
918 DebugInfoDesc *ParentDesc = NULL;
919 if (BlockDesc *Block = dyn_cast<BlockDesc>(ScopeDesc)) {
920 ParentDesc = Block->getContext();
922 DebugScope *Parent = ParentDesc ? getOrCreateScope(ParentDesc) : NULL;
923 Slot = new DebugScope(Parent, ScopeDesc);
925 Parent->AddScope(Slot);
926 } else if (RootScope) {
927 // FIXME - Add inlined function scopes to the root so we can delete
928 // them later. Long term, handle inlined functions properly.
929 RootScope->AddScope(Slot);
931 // First function is top level function.
938 //===-EH-------------------------------------------------------------------===//
940 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
941 /// specified MachineBasicBlock.
942 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
943 (MachineBasicBlock *LandingPad) {
944 unsigned N = LandingPads.size();
945 for (unsigned i = 0; i < N; ++i) {
946 LandingPadInfo &LP = LandingPads[i];
947 if (LP.LandingPadBlock == LandingPad)
951 LandingPads.push_back(LandingPadInfo(LandingPad));
952 return LandingPads[N];
955 /// addInvoke - Provide the begin and end labels of an invoke style call and
956 /// associate it with a try landing pad block.
957 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
958 unsigned BeginLabel, unsigned EndLabel) {
959 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
960 LP.BeginLabels.push_back(BeginLabel);
961 LP.EndLabels.push_back(EndLabel);
964 /// addLandingPad - Provide the label of a try LandingPad block.
966 unsigned MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
967 unsigned LandingPadLabel = NextLabelID();
968 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
969 LP.LandingPadLabel = LandingPadLabel;
970 return LandingPadLabel;
973 /// addPersonality - Provide the personality function for the exception
975 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,
976 Function *Personality) {
977 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
978 LP.Personality = Personality;
980 for (unsigned i = 0; i < Personalities.size(); ++i)
981 if (Personalities[i] == Personality)
984 Personalities.push_back(Personality);
987 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
989 void MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad,
990 std::vector<GlobalVariable *> &TyInfo) {
991 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
992 for (unsigned N = TyInfo.size(); N; --N)
993 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
996 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
998 void MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad,
999 std::vector<GlobalVariable *> &TyInfo) {
1000 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1001 std::vector<unsigned> IdsInFilter (TyInfo.size());
1002 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
1003 IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
1004 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
1007 /// addCleanup - Add a cleanup action for a landing pad.
1009 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
1010 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1011 LP.TypeIds.push_back(0);
1014 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
1016 void MachineModuleInfo::TidyLandingPads() {
1017 for (unsigned i = 0; i != LandingPads.size(); ) {
1018 LandingPadInfo &LandingPad = LandingPads[i];
1019 LandingPad.LandingPadLabel = MappedLabel(LandingPad.LandingPadLabel);
1021 // Special case: we *should* emit LPs with null LP MBB. This indicates
1023 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
1024 LandingPads.erase(LandingPads.begin() + i);
1028 for (unsigned j=0; j != LandingPads[i].BeginLabels.size(); ) {
1029 unsigned BeginLabel = MappedLabel(LandingPad.BeginLabels[j]);
1030 unsigned EndLabel = MappedLabel(LandingPad.EndLabels[j]);
1032 if (!BeginLabel || !EndLabel) {
1033 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
1034 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
1038 LandingPad.BeginLabels[j] = BeginLabel;
1039 LandingPad.EndLabels[j] = EndLabel;
1043 // Remove landing pads with no try-ranges.
1044 if (LandingPads[i].BeginLabels.empty()) {
1045 LandingPads.erase(LandingPads.begin() + i);
1049 // If there is no landing pad, ensure that the list of typeids is empty.
1050 // If the only typeid is a cleanup, this is the same as having no typeids.
1051 if (!LandingPad.LandingPadBlock ||
1052 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
1053 LandingPad.TypeIds.clear();
1059 /// getTypeIDFor - Return the type id for the specified typeinfo. This is
1061 unsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {
1062 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
1063 if (TypeInfos[i] == TI) return i + 1;
1065 TypeInfos.push_back(TI);
1066 return TypeInfos.size();
1069 /// getFilterIDFor - Return the filter id for the specified typeinfos. This is
1071 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
1072 // If the new filter coincides with the tail of an existing filter, then
1073 // re-use the existing filter. Folding filters more than this requires
1074 // re-ordering filters and/or their elements - probably not worth it.
1075 for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
1076 E = FilterEnds.end(); I != E; ++I) {
1077 unsigned i = *I, j = TyIds.size();
1080 if (FilterIds[--i] != TyIds[--j])
1084 // The new filter coincides with range [i, end) of the existing filter.
1090 // Add the new filter.
1091 int FilterID = -(1 + FilterIds.size());
1092 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
1093 for (unsigned I = 0, N = TyIds.size(); I != N; ++I)
1094 FilterIds.push_back(TyIds[I]);
1095 FilterEnds.push_back(FilterIds.size());
1096 FilterIds.push_back(0); // terminator
1100 /// getPersonality - Return the personality function for the current function.
1101 Function *MachineModuleInfo::getPersonality() const {
1102 // FIXME: Until PR1414 will be fixed, we're using 1 personality function per
1104 return !LandingPads.empty() ? LandingPads[0].Personality : NULL;
1107 /// getPersonalityIndex - Return unique index for current personality
1108 /// function. NULL personality function should always get zero index.
1109 unsigned MachineModuleInfo::getPersonalityIndex() const {
1110 const Function* Personality = NULL;
1112 // Scan landing pads. If there is at least one non-NULL personality - use it.
1113 for (unsigned i = 0; i != LandingPads.size(); ++i)
1114 if (LandingPads[i].Personality) {
1115 Personality = LandingPads[i].Personality;
1119 for (unsigned i = 0; i < Personalities.size(); ++i) {
1120 if (Personalities[i] == Personality)
1124 // This should never happen
1125 assert(0 && "Personality function should be set!");
1129 //===----------------------------------------------------------------------===//
1130 /// DebugLabelFolding pass - This pass prunes out redundant labels. This allows
1131 /// a info consumer to determine if the range of two labels is empty, by seeing
1132 /// if the labels map to the same reduced label.
1136 struct DebugLabelFolder : public MachineFunctionPass {
1138 DebugLabelFolder() : MachineFunctionPass((intptr_t)&ID) {}
1140 virtual bool runOnMachineFunction(MachineFunction &MF);
1141 virtual const char *getPassName() const { return "Label Folder"; }
1144 char DebugLabelFolder::ID = 0;
1146 bool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) {
1147 // Get machine module info.
1148 MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>();
1149 if (!MMI) return false;
1151 // Track if change is made.
1152 bool MadeChange = false;
1153 // No prior label to begin.
1154 unsigned PriorLabel = 0;
1156 // Iterate through basic blocks.
1157 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
1159 // Iterate through instructions.
1160 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1162 if (I->isDebugLabel()) {
1163 // The label ID # is always operand #0, an immediate.
1164 unsigned NextLabel = I->getOperand(0).getImm();
1166 // If there was an immediate prior label.
1168 // Remap the current label to prior label.
1169 MMI->RemapLabel(NextLabel, PriorLabel);
1170 // Delete the current label.
1172 // Indicate a change has been made.
1176 // Start a new round.
1177 PriorLabel = NextLabel;
1180 // No consecutive labels.
1191 FunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); }