1//===- lib/MC/MCSymbol.cpp - MCSymbol implementation ----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/MC/MCSymbol.h"
11#include "llvm/MC/MCExpr.h"
12#include "llvm/Support/Debug.h"
13#include "llvm/Support/raw_ostream.h"
14using namespace llvm;
15
16// Sentinel value for the absolute pseudo section.
17const MCSection *MCSymbol::AbsolutePseudoSection =
18  reinterpret_cast<const MCSection *>(1);
19
20static bool isAcceptableChar(char C) {
21  if ((C < 'a' || C > 'z') &&
22      (C < 'A' || C > 'Z') &&
23      (C < '0' || C > '9') &&
24      C != '_' && C != '$' && C != '.' && C != '@')
25    return false;
26  return true;
27}
28
29/// NameNeedsQuoting - Return true if the identifier \p Str needs quotes to be
30/// syntactically correct.
31static bool NameNeedsQuoting(StringRef Str) {
32  assert(!Str.empty() && "Cannot create an empty MCSymbol");
33
34  // If any of the characters in the string is an unacceptable character, force
35  // quotes.
36  for (unsigned i = 0, e = Str.size(); i != e; ++i)
37    if (!isAcceptableChar(Str[i]))
38      return true;
39  return false;
40}
41
42const MCSymbol &MCSymbol::AliasedSymbol() const {
43  const MCSymbol *S = this;
44  while (S->isVariable()) {
45    const MCExpr *Value = S->getVariableValue();
46    if (Value->getKind() != MCExpr::SymbolRef)
47      return *S;
48    const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
49    S = &Ref->getSymbol();
50  }
51  return *S;
52}
53
54void MCSymbol::setVariableValue(const MCExpr *Value) {
55  assert(!IsUsed && "Cannot set a variable that has already been used.");
56  assert(Value && "Invalid variable value!");
57  this->Value = Value;
58  this->Section = nullptr;
59}
60
61void MCSymbol::print(raw_ostream &OS) const {
62  // The name for this MCSymbol is required to be a valid target name.  However,
63  // some targets support quoting names with funny characters.  If the name
64  // contains a funny character, then print it quoted.
65  StringRef Name = getName();
66  if (!NameNeedsQuoting(Name)) {
67    OS << Name;
68    return;
69  }
70
71  OS << '"';
72  for (unsigned I = 0, E = Name.size(); I != E; ++I) {
73    char C = Name[I];
74    if (C == '\n')
75      OS << "\\n";
76    else if (C == '"')
77      OS << "\\\"";
78    else
79      OS << C;
80  }
81  OS << '"';
82}
83
84#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
85void MCSymbol::dump() const {
86  print(dbgs());
87}
88#endif
89