brintos

brintos / llvm-project-archived public Read only

0
0
Text · 25.5 KiB · c24c82d Raw
752 lines · cpp
1//===- MCExpr.cpp - Assembly Level Expression Implementation --------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "llvm/MC/MCExpr.h"10#include "llvm/ADT/ScopeExit.h"11#include "llvm/ADT/Statistic.h"12#include "llvm/Config/llvm-config.h"13#include "llvm/MC/MCAsmBackend.h"14#include "llvm/MC/MCAsmInfo.h"15#include "llvm/MC/MCAssembler.h"16#include "llvm/MC/MCContext.h"17#include "llvm/MC/MCObjectWriter.h"18#include "llvm/MC/MCStreamer.h"19#include "llvm/MC/MCSymbol.h"20#include "llvm/MC/MCValue.h"21#include "llvm/Support/Casting.h"22#include "llvm/Support/Compiler.h"23#include "llvm/Support/Debug.h"24#include "llvm/Support/ErrorHandling.h"25#include "llvm/Support/raw_ostream.h"26#include <cassert>27#include <cstdint>28 29using namespace llvm;30 31#define DEBUG_TYPE "mcexpr"32 33namespace {34namespace stats {35 36STATISTIC(MCExprEvaluate, "Number of MCExpr evaluations");37 38} // end namespace stats39} // end anonymous namespace40 41static int getPrecedence(MCBinaryExpr::Opcode Op) {42  switch (Op) {43  case MCBinaryExpr::Add:44  case MCBinaryExpr::Sub:45    return 1;46  default:47    return 0;48  }49}50 51// VariantKind printing and formatting utilize MAI. operator<< (dump and some52// target code) specifies MAI as nullptr and should be avoided when MAI is53// needed.54void MCExpr::print(raw_ostream &OS, const MCAsmInfo *MAI,55                   int SurroundingPrec) const {56  constexpr int MaxPrec = 9;57  switch (getKind()) {58  case MCExpr::Target:59    return cast<MCTargetExpr>(this)->printImpl(OS, MAI);60  case MCExpr::Constant: {61    auto Value = cast<MCConstantExpr>(*this).getValue();62    auto PrintInHex = cast<MCConstantExpr>(*this).useHexFormat();63    auto SizeInBytes = cast<MCConstantExpr>(*this).getSizeInBytes();64    if (Value < 0 && MAI && !MAI->supportsSignedData())65      PrintInHex = true;66    if (PrintInHex)67      switch (SizeInBytes) {68      default:69        OS << "0x" << Twine::utohexstr(Value);70        break;71      case 1:72        OS << format("0x%02" PRIx64, Value);73        break;74      case 2:75        OS << format("0x%04" PRIx64, Value);76        break;77      case 4:78        OS << format("0x%08" PRIx64, Value);79        break;80      case 8:81        OS << format("0x%016" PRIx64, Value);82        break;83      }84    else85      OS << Value;86    return;87  }88  case MCExpr::SymbolRef: {89    const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*this);90    const MCSymbol &Sym = SRE.getSymbol();91    Sym.print(OS, MAI);92 93    const MCSymbolRefExpr::VariantKind Kind = SRE.getKind();94    if (Kind) {95      if (!MAI) // should only be used by dump()96        OS << "@<variant " << Kind << '>';97      else if (MAI->useParensForSpecifier()) // ARM98        OS << '(' << MAI->getSpecifierName(Kind) << ')';99      else100        OS << '@' << MAI->getSpecifierName(Kind);101    }102 103    return;104  }105 106  case MCExpr::Unary: {107    const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);108    switch (UE.getOpcode()) {109    case MCUnaryExpr::LNot:  OS << '!'; break;110    case MCUnaryExpr::Minus: OS << '-'; break;111    case MCUnaryExpr::Not:   OS << '~'; break;112    case MCUnaryExpr::Plus:  OS << '+'; break;113    }114    UE.getSubExpr()->print(OS, MAI, MaxPrec);115    return;116  }117 118  case MCExpr::Binary: {119    const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);120    // We want to avoid redundant parentheses for relocatable expressions like121    // a-b+c.122    //123    // Print '(' if the current operator has lower precedence than the124    // surrounding operator, or if the surrounding operator's precedence is125    // unknown (set to HighPrecedence).126    int Prec = getPrecedence(BE.getOpcode());127    bool Paren = Prec < SurroundingPrec;128    if (Paren)129      OS << '(';130    // Many operators' precedence is different from C. Set the precedence to131    // HighPrecedence for unknown operators.132    int SubPrec = Prec ? Prec : MaxPrec;133    BE.getLHS()->print(OS, MAI, SubPrec);134 135    switch (BE.getOpcode()) {136    case MCBinaryExpr::Add:137      // Print "X-42" instead of "X+-42".138      if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {139        if (RHSC->getValue() < 0) {140          OS << RHSC->getValue();141          if (Paren)142            OS << ')';143          return;144        }145      }146 147      OS <<  '+';148      break;149    case MCBinaryExpr::AShr: OS << ">>"; break;150    case MCBinaryExpr::And:  OS <<  '&'; break;151    case MCBinaryExpr::Div:  OS <<  '/'; break;152    case MCBinaryExpr::EQ:   OS << "=="; break;153    case MCBinaryExpr::GT:   OS <<  '>'; break;154    case MCBinaryExpr::GTE:  OS << ">="; break;155    case MCBinaryExpr::LAnd: OS << "&&"; break;156    case MCBinaryExpr::LOr:  OS << "||"; break;157    case MCBinaryExpr::LShr: OS << ">>"; break;158    case MCBinaryExpr::LT:   OS <<  '<'; break;159    case MCBinaryExpr::LTE:  OS << "<="; break;160    case MCBinaryExpr::Mod:  OS <<  '%'; break;161    case MCBinaryExpr::Mul:  OS <<  '*'; break;162    case MCBinaryExpr::NE:   OS << "!="; break;163    case MCBinaryExpr::Or:   OS <<  '|'; break;164    case MCBinaryExpr::OrNot: OS << '!'; break;165    case MCBinaryExpr::Shl:  OS << "<<"; break;166    case MCBinaryExpr::Sub:  OS <<  '-'; break;167    case MCBinaryExpr::Xor:  OS <<  '^'; break;168    }169 170    BE.getRHS()->print(OS, MAI, SubPrec + 1);171    if (Paren)172      OS << ')';173    return;174  }175 176  case MCExpr::Specifier: {177    auto &SE = cast<MCSpecifierExpr>(*this);178    if (MAI)179      return MAI->printSpecifierExpr(OS, SE);180    // Used by dump features like -show-inst. Regular MCAsmStreamer output must181    // set MAI.182    OS << "specifier(" << SE.getSpecifier() << ',';183    SE.getSubExpr()->print(OS, nullptr);184    OS << ')';185    return;186  }187  }188 189  llvm_unreachable("Invalid expression kind!");190}191 192#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)193LLVM_DUMP_METHOD void MCExpr::dump() const {194  print(dbgs(), nullptr);195  dbgs() << '\n';196}197#endif198 199/* *** */200 201const MCBinaryExpr *MCBinaryExpr::create(Opcode Opc, const MCExpr *LHS,202                                         const MCExpr *RHS, MCContext &Ctx,203                                         SMLoc Loc) {204  return new (Ctx) MCBinaryExpr(Opc, LHS, RHS, Loc);205}206 207const MCUnaryExpr *MCUnaryExpr::create(Opcode Opc, const MCExpr *Expr,208                                       MCContext &Ctx, SMLoc Loc) {209  return new (Ctx) MCUnaryExpr(Opc, Expr, Loc);210}211 212const MCConstantExpr *MCConstantExpr::create(int64_t Value, MCContext &Ctx,213                                             bool PrintInHex,214                                             unsigned SizeInBytes) {215  return new (Ctx) MCConstantExpr(Value, PrintInHex, SizeInBytes);216}217 218/* *** */219 220MCSymbolRefExpr::MCSymbolRefExpr(const MCSymbol *Symbol, Spec specifier,221                                 const MCAsmInfo *MAI, SMLoc Loc)222    : MCExpr(MCExpr::SymbolRef, Loc, specifier), Symbol(Symbol) {223  assert(Symbol);224}225 226const MCSymbolRefExpr *MCSymbolRefExpr::create(const MCSymbol *Sym,227                                               uint16_t specifier,228                                               MCContext &Ctx, SMLoc Loc) {229  return new (Ctx) MCSymbolRefExpr(Sym, specifier, Ctx.getAsmInfo(), Loc);230}231 232/* *** */233 234void MCTargetExpr::anchor() {}235 236/* *** */237 238bool MCExpr::evaluateAsAbsolute(int64_t &Res) const {239  return evaluateAsAbsolute(Res, nullptr, false);240}241 242bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {243  return evaluateAsAbsolute(Res, &Asm, false);244}245 246bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm) const {247  return evaluateAsAbsolute(Res, Asm, false);248}249 250bool MCExpr::evaluateKnownAbsolute(int64_t &Res, const MCAssembler &Asm) const {251  return evaluateAsAbsolute(Res, &Asm, true);252}253 254bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,255                                bool InSet) const {256  MCValue Value;257 258  // Fast path constants.259  if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {260    Res = CE->getValue();261    return true;262  }263 264  bool IsRelocatable = evaluateAsRelocatableImpl(Value, Asm, InSet);265  Res = Value.getConstant();266  // Value with RefKind (e.g. %hi(0xdeadbeef) in MIPS) is not considered267  // absolute (the value is unknown at parse time), even if it might be resolved268  // by evaluateFixup.269  return IsRelocatable && Value.isAbsolute() && Value.getSpecifier() == 0;270}271 272/// Helper method for \see EvaluateSymbolAdd().273static void attemptToFoldSymbolOffsetDifference(const MCAssembler *Asm,274                                                bool InSet, const MCSymbol *&A,275                                                const MCSymbol *&B,276                                                int64_t &Addend) {277  if (!A || !B)278    return;279 280  const MCSymbol &SA = *A, &SB = *B;281  if (SA.isUndefined() || SB.isUndefined())282    return;283  if (!Asm->getWriter().isSymbolRefDifferenceFullyResolved(SA, SB, InSet))284    return;285 286  auto FinalizeFolding = [&]() {287    // Pointers to Thumb symbols need to have their low-bit set to allow288    // for interworking.289    if (Asm->isThumbFunc(&SA))290      Addend |= 1;291 292    // Clear the symbol expr pointers to indicate we have folded these293    // operands.294    A = B = nullptr;295  };296 297  const MCFragment *FA = SA.getFragment();298  const MCFragment *FB = SB.getFragment();299  const MCSection &SecA = *FA->getParent();300  const MCSection &SecB = *FB->getParent();301  if (&SecA != &SecB)302    return;303 304  // When layout is available, we can generally compute the difference using the305  // getSymbolOffset path, which also avoids the possible slow fragment walk.306  // However, linker relaxation may cause incorrect fold of A-B if A and B are307  // separated by a linker-relaxable fragment. If the section contains308  // linker-relaxable instruction and InSet is false (not expressions in309  // directive like .size/.fill), disable the fast path.310  bool Layout = Asm->hasLayout();311  if (Layout && (InSet || !SecA.isLinkerRelaxable())) {312    // If both symbols are in the same fragment, return the difference of their313    // offsets. canGetFragmentOffset(FA) may be false.314    if (FA == FB && !SA.isVariable() && !SB.isVariable()) {315      Addend += SA.getOffset() - SB.getOffset();316      return FinalizeFolding();317    }318 319    // Eagerly evaluate when layout is finalized.320    Addend += Asm->getSymbolOffset(SA) - Asm->getSymbolOffset(SB);321    FinalizeFolding();322  } else {323    // When layout is not finalized, our ability to resolve differences between324    // symbols is limited to specific cases where the fragments between two325    // symbols (including the fragments the symbols are defined in) are326    // fixed-size fragments so the difference can be calculated. For example,327    // this is important when the Subtarget is changed and a new MCFragment328    // is created in the case of foo: instr; .arch_extension ext; instr .if . -329    // foo.330    if (SA.isVariable() || SB.isVariable())331      return;332 333    // Try to find a constant displacement from FA to FB, add the displacement334    // between the offset in FA of SA and the offset in FB of SB.335    bool Reverse = false;336    if (FA == FB)337      Reverse = SA.getOffset() < SB.getOffset();338    else339      Reverse = FA->getLayoutOrder() < FB->getLayoutOrder();340 341    uint64_t SAOffset = SA.getOffset(), SBOffset = SB.getOffset();342    int64_t Displacement = SA.getOffset() - SB.getOffset();343    if (Reverse) {344      std::swap(FA, FB);345      std::swap(SAOffset, SBOffset);346      Displacement *= -1;347    }348 349    // Track whether B is before a relaxable instruction/alignment and whether A350    // is after a relaxable instruction/alignment. If SA and SB are separated by351    // a linker-relaxable instruction/alignment, the difference cannot be352    // resolved as it may be changed by the linker.353    bool BBeforeRelax = false, AAfterRelax = false;354    for (auto F = FB; F; F = F->getNext()) {355      if (F && F->isLinkerRelaxable()) {356        if (&*F != FB || SBOffset != F->getSize())357          BBeforeRelax = true;358        if (&*F != FA || SAOffset == F->getSize())359          AAfterRelax = true;360        if (BBeforeRelax && AAfterRelax)361          return;362      }363      if (&*F == FA) {364        // If FA and FB belong to the same subsection, the loop will find FA and365        // we can resolve the difference.366        Addend += Reverse ? -Displacement : Displacement;367        FinalizeFolding();368        return;369      }370 371      int64_t Num;372      if (F->getKind() == MCFragment::FT_Data) {373        Displacement += F->getFixedSize();374      } else if ((F->getKind() == MCFragment::FT_Relaxable ||375                  F->getKind() == MCFragment::FT_Align) &&376                 Asm->hasFinalLayout()) {377        // Before finishLayout, a relaxable fragment's size is indeterminate.378        // After layout, during relocation generation, it can be treated as a379        // data fragment.380        Displacement += F->getSize();381      } else if (auto *FF = dyn_cast<MCFillFragment>(F);382                 FF && FF->getNumValues().evaluateAsAbsolute(Num)) {383        Displacement += Num * FF->getValueSize();384      } else {385        return;386      }387    }388  }389}390 391// Evaluate the sum of two relocatable expressions.392//393//   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).394//395// This routine attempts to aggressively fold the operands such that the result396// is representable in an MCValue, but may not always succeed.397//398// LHS_A and RHS_A might have relocation specifiers while LHS_B and RHS_B399// cannot have specifiers.400//401// \returns True on success, false if the result is not representable in an402// MCValue.403 404// NOTE: This function can be used before layout is done (see the object405// streamer for example) and having the Asm argument lets us avoid relaxations406// early.407bool MCExpr::evaluateSymbolicAdd(const MCAssembler *Asm, bool InSet,408                                 const MCValue &LHS, const MCValue &RHS,409                                 MCValue &Res) {410  const MCSymbol *LHS_A = LHS.getAddSym();411  const MCSymbol *LHS_B = LHS.getSubSym();412  int64_t LHS_Cst = LHS.getConstant();413 414  const MCSymbol *RHS_A = RHS.getAddSym();415  const MCSymbol *RHS_B = RHS.getSubSym();416  int64_t RHS_Cst = RHS.getConstant();417 418  // Fold the result constant immediately.419  int64_t Result_Cst = LHS_Cst + RHS_Cst;420 421  // If we have a layout, we can fold resolved differences.422  if (Asm && !LHS.getSpecifier() && !RHS.getSpecifier()) {423    // While LHS_A-LHS_B and RHS_A-RHS_B from recursive calls have already been424    // folded, reassociating terms in425    //   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).426    // might bring more opportunities.427    if (LHS_A && RHS_B) {428      attemptToFoldSymbolOffsetDifference(Asm, InSet, LHS_A, RHS_B, Result_Cst);429    }430    if (RHS_A && LHS_B) {431      attemptToFoldSymbolOffsetDifference(Asm, InSet, RHS_A, LHS_B, Result_Cst);432    }433  }434 435  // We can't represent the addition or subtraction of two symbols.436  if ((LHS_A && RHS_A) || (LHS_B && RHS_B))437    return false;438 439  // At this point, we have at most one additive symbol and one subtractive440  // symbol -- find them.441  auto *A = LHS_A ? LHS_A : RHS_A;442  auto *B = LHS_B ? LHS_B : RHS_B;443  auto Spec = LHS.getSpecifier();444  if (!Spec)445    Spec = RHS.getSpecifier();446  Res = MCValue::get(A, B, Result_Cst, Spec);447  return true;448}449 450bool MCExpr::evaluateAsRelocatable(MCValue &Res, const MCAssembler *Asm) const {451  return evaluateAsRelocatableImpl(Res, Asm, false);452}453bool MCExpr::evaluateAsValue(MCValue &Res, const MCAssembler &Asm) const {454  return evaluateAsRelocatableImpl(Res, &Asm, true);455}456 457bool MCExpr::evaluateAsRelocatableImpl(MCValue &Res, const MCAssembler *Asm,458                                       bool InSet) const {459  ++stats::MCExprEvaluate;460  switch (getKind()) {461  case Target:462    return cast<MCTargetExpr>(this)->evaluateAsRelocatableImpl(Res, Asm);463  case Constant:464    Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());465    return true;466 467  case SymbolRef: {468    const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);469    MCSymbol &Sym = const_cast<MCSymbol &>(SRE->getSymbol());470    const auto Kind = SRE->getKind();471    bool Layout = Asm && Asm->hasLayout();472 473    // If the symbol is equated, resolve the inner expression.474    // However, when two IMAGE_WEAK_EXTERN_ANTI_DEPENDENCY symbols reference475    // each other, we retain the equated symbol to avoid a cyclic definition476    // error.477    if (Sym.isResolving()) {478      if (Asm && Asm->hasFinalLayout()) {479        Asm->getContext().reportError(480            Sym.getVariableValue()->getLoc(),481            "cyclic dependency detected for symbol '" + Sym.getName() + "'");482        Sym.setVariableValue(MCConstantExpr::create(0, Asm->getContext()));483      }484      return false;485    }486    if (Sym.isVariable() && (Kind == 0 || Layout) && !Sym.isWeakExternal()) {487      Sym.setIsResolving(true);488      auto _ = make_scope_exit([&] { Sym.setIsResolving(false); });489      bool IsMachO =490          Asm && Asm->getContext().getAsmInfo()->hasSubsectionsViaSymbols();491      if (!Sym.getVariableValue()->evaluateAsRelocatableImpl(Res, Asm,492                                                             InSet || IsMachO))493        return false;494      // When generating relocations, if Sym resolves to a symbol relative to a495      // section, relocations are generated against Sym. Treat label differences496      // as constants.497      auto *A = Res.getAddSym();498      auto *B = Res.getSubSym();499      if (InSet || !(A && !B && A->isInSection())) {500        if (Kind) {501          if (Res.isAbsolute()) {502            Res = MCValue::get(&Sym, nullptr, 0, Kind);503            return true;504          }505          // If the reference has a variant kind, we can only handle expressions506          // which evaluate exactly to a single unadorned symbol. Attach the507          // original VariantKind to SymA of the result.508          if (Res.getSpecifier() || !Res.getAddSym() || Res.getSubSym() ||509              Res.getConstant())510            return false;511          Res.Specifier = Kind;512        }513        if (!IsMachO)514          return true;515 516        // FIXME: This is small hack. Given517        // a = b + 4518        // .long a519        // the OS X assembler will completely drop the 4. We should probably520        // include it in the relocation or produce an error if that is not521        // possible.522        // Allow constant expressions.523        if (!A && !B)524          return true;525        // Allows aliases with zero offset.526        if (Res.getConstant() == 0 && (!A || !B))527          return true;528      }529    }530 531    Res = MCValue::get(&Sym, nullptr, 0, Kind);532    return true;533  }534 535  case Unary: {536    const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);537    MCValue Value;538 539    if (!AUE->getSubExpr()->evaluateAsRelocatableImpl(Value, Asm, InSet))540      return false;541    switch (AUE->getOpcode()) {542    case MCUnaryExpr::LNot:543      if (!Value.isAbsolute())544        return false;545      Res = MCValue::get(!Value.getConstant());546      break;547    case MCUnaryExpr::Minus:548      /// -(a - b + const) ==> (b - a - const)549      if (Value.getAddSym() && !Value.getSubSym())550        return false;551 552      // The cast avoids undefined behavior if the constant is INT64_MIN.553      Res = MCValue::get(Value.getSubSym(), Value.getAddSym(),554                         -(uint64_t)Value.getConstant());555      break;556    case MCUnaryExpr::Not:557      if (!Value.isAbsolute())558        return false;559      Res = MCValue::get(~Value.getConstant());560      break;561    case MCUnaryExpr::Plus:562      Res = Value;563      break;564    }565 566    return true;567  }568 569  case Binary: {570    const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);571    MCValue LHSValue, RHSValue;572 573    if (!ABE->getLHS()->evaluateAsRelocatableImpl(LHSValue, Asm, InSet) ||574        !ABE->getRHS()->evaluateAsRelocatableImpl(RHSValue, Asm, InSet)) {575      // Check if both are Target Expressions, see if we can compare them.576      if (const MCTargetExpr *L = dyn_cast<MCTargetExpr>(ABE->getLHS())) {577        if (const MCTargetExpr *R = dyn_cast<MCTargetExpr>(ABE->getRHS())) {578          switch (ABE->getOpcode()) {579          case MCBinaryExpr::EQ:580            Res = MCValue::get(L->isEqualTo(R) ? -1 : 0);581            return true;582          case MCBinaryExpr::NE:583            Res = MCValue::get(L->isEqualTo(R) ? 0 : -1);584            return true;585          default:586            break;587          }588        }589      }590      return false;591    }592 593    // We only support a few operations on non-constant expressions, handle594    // those first.595    auto Op = ABE->getOpcode();596    int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();597    if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {598      switch (Op) {599      default:600        return false;601      case MCBinaryExpr::Add:602      case MCBinaryExpr::Sub:603        if (Op == MCBinaryExpr::Sub) {604          std::swap(RHSValue.SymA, RHSValue.SymB);605          RHSValue.Cst = -(uint64_t)RHSValue.Cst;606        }607        if (RHSValue.isAbsolute()) {608          LHSValue.Cst += RHSValue.Cst;609          Res = LHSValue;610          return true;611        }612        if (LHSValue.isAbsolute()) {613          RHSValue.Cst += LHSValue.Cst;614          Res = RHSValue;615          return true;616        }617        if (LHSValue.SymB && LHSValue.Specifier)618          return false;619        if (RHSValue.SymB && RHSValue.Specifier)620          return false;621        return evaluateSymbolicAdd(Asm, InSet, LHSValue, RHSValue, Res);622      }623    }624 625    // FIXME: We need target hooks for the evaluation. It may be limited in626    // width, and gas defines the result of comparisons differently from627    // Apple as.628    int64_t Result = 0;629    switch (Op) {630    case MCBinaryExpr::AShr: Result = LHS >> RHS; break;631    case MCBinaryExpr::Add:  Result = LHS + RHS; break;632    case MCBinaryExpr::And:  Result = LHS & RHS; break;633    case MCBinaryExpr::Div:634    case MCBinaryExpr::Mod:635      // Handle division by zero. gas just emits a warning and keeps going,636      // we try to be stricter.637      // FIXME: Currently the caller of this function has no way to understand638      // we're bailing out because of 'division by zero'. Therefore, it will639      // emit a 'expected relocatable expression' error. It would be nice to640      // change this code to emit a better diagnostic.641      if (RHS == 0)642        return false;643      if (ABE->getOpcode() == MCBinaryExpr::Div)644        Result = LHS / RHS;645      else646        Result = LHS % RHS;647      break;648    case MCBinaryExpr::EQ:   Result = LHS == RHS; break;649    case MCBinaryExpr::GT:   Result = LHS > RHS; break;650    case MCBinaryExpr::GTE:  Result = LHS >= RHS; break;651    case MCBinaryExpr::LAnd: Result = LHS && RHS; break;652    case MCBinaryExpr::LOr:  Result = LHS || RHS; break;653    case MCBinaryExpr::LShr: Result = uint64_t(LHS) >> uint64_t(RHS); break;654    case MCBinaryExpr::LT:   Result = LHS < RHS; break;655    case MCBinaryExpr::LTE:  Result = LHS <= RHS; break;656    case MCBinaryExpr::Mul:  Result = LHS * RHS; break;657    case MCBinaryExpr::NE:   Result = LHS != RHS; break;658    case MCBinaryExpr::Or:   Result = LHS | RHS; break;659    case MCBinaryExpr::OrNot: Result = LHS | ~RHS; break;660    case MCBinaryExpr::Shl:  Result = uint64_t(LHS) << uint64_t(RHS); break;661    case MCBinaryExpr::Sub:  Result = LHS - RHS; break;662    case MCBinaryExpr::Xor:  Result = LHS ^ RHS; break;663    }664 665    switch (Op) {666    default:667      Res = MCValue::get(Result);668      break;669    case MCBinaryExpr::EQ:670    case MCBinaryExpr::GT:671    case MCBinaryExpr::GTE:672    case MCBinaryExpr::LT:673    case MCBinaryExpr::LTE:674    case MCBinaryExpr::NE:675      // A comparison operator returns a -1 if true and 0 if false.676      Res = MCValue::get(Result ? -1 : 0);677      break;678    }679 680    return true;681  }682  case Specifier:683    // Fold the expression during relocation generation. As parse time Asm might684    // be null, and targets should not rely on the folding.685    return Asm && Asm->getContext().getAsmInfo()->evaluateAsRelocatableImpl(686                      cast<MCSpecifierExpr>(*this), Res, Asm);687  }688 689  llvm_unreachable("Invalid assembly expression kind!");690}691 692MCFragment *MCExpr::findAssociatedFragment() const {693  switch (getKind()) {694  case Target:695    // We never look through target specific expressions.696    return cast<MCTargetExpr>(this)->findAssociatedFragment();697 698  case Constant:699    return MCSymbol::AbsolutePseudoFragment;700 701  case SymbolRef: {702    auto &Sym =703        const_cast<MCSymbol &>(cast<MCSymbolRefExpr>(this)->getSymbol());704    if (Sym.Fragment)705      return Sym.Fragment;706    if (Sym.isResolving())707      return MCSymbol::AbsolutePseudoFragment;708    Sym.setIsResolving(true);709    auto *F = Sym.getFragment();710    Sym.setIsResolving(false);711    return F;712  }713 714  case Unary:715    return cast<MCUnaryExpr>(this)->getSubExpr()->findAssociatedFragment();716 717  case Binary: {718    const MCBinaryExpr *BE = cast<MCBinaryExpr>(this);719    MCFragment *LHS_F = BE->getLHS()->findAssociatedFragment();720    MCFragment *RHS_F = BE->getRHS()->findAssociatedFragment();721 722    // If either is absolute, return the other.723    if (LHS_F == MCSymbol::AbsolutePseudoFragment)724      return RHS_F;725    if (RHS_F == MCSymbol::AbsolutePseudoFragment)726      return LHS_F;727 728    // Not always correct, but probably the best we can do without more context.729    if (BE->getOpcode() == MCBinaryExpr::Sub)730      return MCSymbol::AbsolutePseudoFragment;731 732    // Otherwise, return the first non-null fragment.733    return LHS_F ? LHS_F : RHS_F;734  }735 736  case Specifier:737    return cast<MCSpecifierExpr>(this)->getSubExpr()->findAssociatedFragment();738  }739 740  llvm_unreachable("Invalid assembly expression kind!");741}742 743const MCSpecifierExpr *MCSpecifierExpr::create(const MCExpr *Expr, Spec S,744                                               MCContext &Ctx, SMLoc Loc) {745  return new (Ctx) MCSpecifierExpr(Expr, S, Loc);746}747 748const MCSpecifierExpr *MCSpecifierExpr::create(const MCSymbol *Sym, Spec S,749                                               MCContext &Ctx, SMLoc Loc) {750  return new (Ctx) MCSpecifierExpr(MCSymbolRefExpr::create(Sym, Ctx), S, Loc);751}752