1 //===- MCExpr.cpp - Assembly Level Expression Implementation --------------===//
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 #define DEBUG_TYPE "mcexpr"
11 #include "llvm/MC/MCExpr.h"
12 #include "llvm/ADT/Statistic.h"
13 #include "llvm/ADT/StringSwitch.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
27 STATISTIC(MCExprEvaluate, "Number of MCExpr evaluations");
31 void MCExpr::print(raw_ostream &OS) const {
34 return cast<MCTargetExpr>(this)->PrintImpl(OS);
35 case MCExpr::Constant:
36 OS << cast<MCConstantExpr>(*this).getValue();
39 case MCExpr::SymbolRef: {
40 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*this);
41 const MCSymbol &Sym = SRE.getSymbol();
42 // Parenthesize names that start with $ so that they don't look like
44 bool UseParens = Sym.getName()[0] == '$';
46 if (SRE.getKind() == MCSymbolRefExpr::VK_PPC_DARWIN_HA16 ||
47 SRE.getKind() == MCSymbolRefExpr::VK_PPC_DARWIN_LO16) {
48 OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
53 OS << '(' << Sym << ')';
57 if (SRE.getKind() == MCSymbolRefExpr::VK_ARM_PLT ||
58 SRE.getKind() == MCSymbolRefExpr::VK_ARM_TLSGD ||
59 SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOT ||
60 SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOTOFF ||
61 SRE.getKind() == MCSymbolRefExpr::VK_ARM_TPOFF ||
62 SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOTTPOFF ||
63 SRE.getKind() == MCSymbolRefExpr::VK_ARM_TARGET1 ||
64 SRE.getKind() == MCSymbolRefExpr::VK_ARM_TARGET2)
65 OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
66 else if (SRE.getKind() != MCSymbolRefExpr::VK_None &&
67 SRE.getKind() != MCSymbolRefExpr::VK_PPC_DARWIN_HA16 &&
68 SRE.getKind() != MCSymbolRefExpr::VK_PPC_DARWIN_LO16)
69 OS << '@' << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
75 const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);
76 switch (UE.getOpcode()) {
77 case MCUnaryExpr::LNot: OS << '!'; break;
78 case MCUnaryExpr::Minus: OS << '-'; break;
79 case MCUnaryExpr::Not: OS << '~'; break;
80 case MCUnaryExpr::Plus: OS << '+'; break;
82 OS << *UE.getSubExpr();
86 case MCExpr::Binary: {
87 const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);
89 // Only print parens around the LHS if it is non-trivial.
90 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS())) {
93 OS << '(' << *BE.getLHS() << ')';
96 switch (BE.getOpcode()) {
97 case MCBinaryExpr::Add:
98 // Print "X-42" instead of "X+-42".
99 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
100 if (RHSC->getValue() < 0) {
101 OS << RHSC->getValue();
108 case MCBinaryExpr::And: OS << '&'; break;
109 case MCBinaryExpr::Div: OS << '/'; break;
110 case MCBinaryExpr::EQ: OS << "=="; break;
111 case MCBinaryExpr::GT: OS << '>'; break;
112 case MCBinaryExpr::GTE: OS << ">="; break;
113 case MCBinaryExpr::LAnd: OS << "&&"; break;
114 case MCBinaryExpr::LOr: OS << "||"; break;
115 case MCBinaryExpr::LT: OS << '<'; break;
116 case MCBinaryExpr::LTE: OS << "<="; break;
117 case MCBinaryExpr::Mod: OS << '%'; break;
118 case MCBinaryExpr::Mul: OS << '*'; break;
119 case MCBinaryExpr::NE: OS << "!="; break;
120 case MCBinaryExpr::Or: OS << '|'; break;
121 case MCBinaryExpr::Shl: OS << "<<"; break;
122 case MCBinaryExpr::Shr: OS << ">>"; break;
123 case MCBinaryExpr::Sub: OS << '-'; break;
124 case MCBinaryExpr::Xor: OS << '^'; break;
127 // Only print parens around the LHS if it is non-trivial.
128 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
131 OS << '(' << *BE.getRHS() << ')';
137 llvm_unreachable("Invalid expression kind!");
140 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
141 void MCExpr::dump() const {
149 const MCBinaryExpr *MCBinaryExpr::Create(Opcode Opc, const MCExpr *LHS,
150 const MCExpr *RHS, MCContext &Ctx) {
151 return new (Ctx) MCBinaryExpr(Opc, LHS, RHS);
154 const MCUnaryExpr *MCUnaryExpr::Create(Opcode Opc, const MCExpr *Expr,
156 return new (Ctx) MCUnaryExpr(Opc, Expr);
159 const MCConstantExpr *MCConstantExpr::Create(int64_t Value, MCContext &Ctx) {
160 return new (Ctx) MCConstantExpr(Value);
165 const MCSymbolRefExpr *MCSymbolRefExpr::Create(const MCSymbol *Sym,
168 return new (Ctx) MCSymbolRefExpr(Sym, Kind);
171 const MCSymbolRefExpr *MCSymbolRefExpr::Create(StringRef Name, VariantKind Kind,
173 return Create(Ctx.GetOrCreateSymbol(Name), Kind, Ctx);
176 StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) {
178 case VK_Invalid: return "<<invalid>>";
179 case VK_None: return "<<none>>";
181 case VK_GOT: return "GOT";
182 case VK_GOTOFF: return "GOTOFF";
183 case VK_GOTPCREL: return "GOTPCREL";
184 case VK_GOTTPOFF: return "GOTTPOFF";
185 case VK_INDNTPOFF: return "INDNTPOFF";
186 case VK_NTPOFF: return "NTPOFF";
187 case VK_GOTNTPOFF: return "GOTNTPOFF";
188 case VK_PLT: return "PLT";
189 case VK_TLSGD: return "TLSGD";
190 case VK_TLSLD: return "TLSLD";
191 case VK_TLSLDM: return "TLSLDM";
192 case VK_TPOFF: return "TPOFF";
193 case VK_DTPOFF: return "DTPOFF";
194 case VK_TLVP: return "TLVP";
195 case VK_SECREL: return "SECREL";
196 case VK_ARM_PLT: return "(PLT)";
197 case VK_ARM_GOT: return "(GOT)";
198 case VK_ARM_GOTOFF: return "(GOTOFF)";
199 case VK_ARM_TPOFF: return "(tpoff)";
200 case VK_ARM_GOTTPOFF: return "(gottpoff)";
201 case VK_ARM_TLSGD: return "(tlsgd)";
202 case VK_ARM_TARGET1: return "(target1)";
203 case VK_ARM_TARGET2: return "(target2)";
204 case VK_PPC_TOC: return "tocbase";
205 case VK_PPC_TOC_ENTRY: return "toc";
206 case VK_PPC_DARWIN_HA16: return "ha16";
207 case VK_PPC_DARWIN_LO16: return "lo16";
208 case VK_PPC_GAS_HA16: return "ha";
209 case VK_PPC_GAS_LO16: return "l";
210 case VK_PPC_TPREL16_HA: return "tprel@ha";
211 case VK_PPC_TPREL16_LO: return "tprel@l";
212 case VK_PPC_TOC16_HA: return "toc@ha";
213 case VK_PPC_TOC16_LO: return "toc@l";
214 case VK_PPC_GOT_TPREL16_DS: return "got@tprel";
215 case VK_PPC_TLS: return "tls";
216 case VK_Mips_GPREL: return "GPREL";
217 case VK_Mips_GOT_CALL: return "GOT_CALL";
218 case VK_Mips_GOT16: return "GOT16";
219 case VK_Mips_GOT: return "GOT";
220 case VK_Mips_ABS_HI: return "ABS_HI";
221 case VK_Mips_ABS_LO: return "ABS_LO";
222 case VK_Mips_TLSGD: return "TLSGD";
223 case VK_Mips_TLSLDM: return "TLSLDM";
224 case VK_Mips_DTPREL_HI: return "DTPREL_HI";
225 case VK_Mips_DTPREL_LO: return "DTPREL_LO";
226 case VK_Mips_GOTTPREL: return "GOTTPREL";
227 case VK_Mips_TPREL_HI: return "TPREL_HI";
228 case VK_Mips_TPREL_LO: return "TPREL_LO";
229 case VK_Mips_GPOFF_HI: return "GPOFF_HI";
230 case VK_Mips_GPOFF_LO: return "GPOFF_LO";
231 case VK_Mips_GOT_DISP: return "GOT_DISP";
232 case VK_Mips_GOT_PAGE: return "GOT_PAGE";
233 case VK_Mips_GOT_OFST: return "GOT_OFST";
234 case VK_Mips_HIGHER: return "HIGHER";
235 case VK_Mips_HIGHEST: return "HIGHEST";
236 case VK_Mips_GOT_HI16: return "GOT_HI16";
237 case VK_Mips_GOT_LO16: return "GOT_LO16";
238 case VK_Mips_CALL_HI16: return "CALL_HI16";
239 case VK_Mips_CALL_LO16: return "CALL_LO16";
241 llvm_unreachable("Invalid variant kind");
244 MCSymbolRefExpr::VariantKind
245 MCSymbolRefExpr::getVariantKindForName(StringRef Name) {
246 return StringSwitch<VariantKind>(Name)
249 .Case("GOTOFF", VK_GOTOFF)
250 .Case("gotoff", VK_GOTOFF)
251 .Case("GOTPCREL", VK_GOTPCREL)
252 .Case("gotpcrel", VK_GOTPCREL)
253 .Case("GOTTPOFF", VK_GOTTPOFF)
254 .Case("gottpoff", VK_GOTTPOFF)
255 .Case("INDNTPOFF", VK_INDNTPOFF)
256 .Case("indntpoff", VK_INDNTPOFF)
257 .Case("NTPOFF", VK_NTPOFF)
258 .Case("ntpoff", VK_NTPOFF)
259 .Case("GOTNTPOFF", VK_GOTNTPOFF)
260 .Case("gotntpoff", VK_GOTNTPOFF)
263 .Case("TLSGD", VK_TLSGD)
264 .Case("tlsgd", VK_TLSGD)
265 .Case("TLSLD", VK_TLSLD)
266 .Case("tlsld", VK_TLSLD)
267 .Case("TLSLDM", VK_TLSLDM)
268 .Case("tlsldm", VK_TLSLDM)
269 .Case("TPOFF", VK_TPOFF)
270 .Case("tpoff", VK_TPOFF)
271 .Case("DTPOFF", VK_DTPOFF)
272 .Case("dtpoff", VK_DTPOFF)
273 .Case("TLVP", VK_TLVP)
274 .Case("tlvp", VK_TLVP)
275 .Default(VK_Invalid);
280 void MCTargetExpr::anchor() {}
284 bool MCExpr::EvaluateAsAbsolute(int64_t &Res) const {
285 return EvaluateAsAbsolute(Res, 0, 0, 0);
288 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
289 const MCAsmLayout &Layout) const {
290 return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, 0);
293 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
294 const MCAsmLayout &Layout,
295 const SectionAddrMap &Addrs) const {
296 return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, &Addrs);
299 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {
300 return EvaluateAsAbsolute(Res, &Asm, 0, 0);
303 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
304 const MCAsmLayout *Layout,
305 const SectionAddrMap *Addrs) const {
308 // Fast path constants.
309 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {
310 Res = CE->getValue();
314 // FIXME: The use if InSet = Addrs is a hack. Setting InSet causes us
315 // absolutize differences across sections and that is what the MachO writer
318 EvaluateAsRelocatableImpl(Value, Asm, Layout, Addrs, /*InSet*/ Addrs);
320 // Record the current value.
321 Res = Value.getConstant();
323 return IsRelocatable && Value.isAbsolute();
326 /// \brief Helper method for \see EvaluateSymbolAdd().
327 static void AttemptToFoldSymbolOffsetDifference(const MCAssembler *Asm,
328 const MCAsmLayout *Layout,
329 const SectionAddrMap *Addrs,
331 const MCSymbolRefExpr *&A,
332 const MCSymbolRefExpr *&B,
337 const MCSymbol &SA = A->getSymbol();
338 const MCSymbol &SB = B->getSymbol();
340 if (SA.isUndefined() || SB.isUndefined())
343 if (!Asm->getWriter().IsSymbolRefDifferenceFullyResolved(*Asm, A, B, InSet))
346 MCSymbolData &AD = Asm->getSymbolData(SA);
347 MCSymbolData &BD = Asm->getSymbolData(SB);
349 if (AD.getFragment() == BD.getFragment()) {
350 Addend += (AD.getOffset() - BD.getOffset());
352 // Pointers to Thumb symbols need to have their low-bit set to allow
354 if (Asm->isThumbFunc(&SA))
357 // Clear the symbol expr pointers to indicate we have folded these
366 const MCSectionData &SecA = *AD.getFragment()->getParent();
367 const MCSectionData &SecB = *BD.getFragment()->getParent();
369 if ((&SecA != &SecB) && !Addrs)
373 Addend += (Layout->getSymbolOffset(&Asm->getSymbolData(A->getSymbol())) -
374 Layout->getSymbolOffset(&Asm->getSymbolData(B->getSymbol())));
375 if (Addrs && (&SecA != &SecB))
376 Addend += (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
378 // Pointers to Thumb symbols need to have their low-bit set to allow
380 if (Asm->isThumbFunc(&SA))
383 // Clear the symbol expr pointers to indicate we have folded these
388 /// \brief Evaluate the result of an add between (conceptually) two MCValues.
390 /// This routine conceptually attempts to construct an MCValue:
391 /// Result = (Result_A - Result_B + Result_Cst)
392 /// from two MCValue's LHS and RHS where
393 /// Result = LHS + RHS
395 /// Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
397 /// This routine attempts to aggresively fold the operands such that the result
398 /// is representable in an MCValue, but may not always succeed.
400 /// \returns True on success, false if the result is not representable in an
403 /// NOTE: It is really important to have both the Asm and Layout arguments.
404 /// They might look redundant, but this function can be used before layout
405 /// is done (see the object streamer for example) and having the Asm argument
406 /// lets us avoid relaxations early.
407 static bool EvaluateSymbolicAdd(const MCAssembler *Asm,
408 const MCAsmLayout *Layout,
409 const SectionAddrMap *Addrs,
411 const MCValue &LHS,const MCSymbolRefExpr *RHS_A,
412 const MCSymbolRefExpr *RHS_B, int64_t RHS_Cst,
414 // FIXME: This routine (and other evaluation parts) are *incredibly* sloppy
415 // about dealing with modifiers. This will ultimately bite us, one day.
416 const MCSymbolRefExpr *LHS_A = LHS.getSymA();
417 const MCSymbolRefExpr *LHS_B = LHS.getSymB();
418 int64_t LHS_Cst = LHS.getConstant();
420 // Fold the result constant immediately.
421 int64_t Result_Cst = LHS_Cst + RHS_Cst;
423 assert((!Layout || Asm) &&
424 "Must have an assembler object if layout is given!");
426 // If we have a layout, we can fold resolved differences.
428 // First, fold out any differences which are fully resolved. By
429 // reassociating terms in
430 // Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
431 // we have the four possible differences:
436 // Since we are attempting to be as aggressive as possible about folding, we
437 // attempt to evaluate each possible alternative.
438 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, LHS_B,
440 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, RHS_B,
442 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, LHS_B,
444 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, RHS_B,
448 // We can't represent the addition or subtraction of two symbols.
449 if ((LHS_A && RHS_A) || (LHS_B && RHS_B))
452 // At this point, we have at most one additive symbol and one subtractive
453 // symbol -- find them.
454 const MCSymbolRefExpr *A = LHS_A ? LHS_A : RHS_A;
455 const MCSymbolRefExpr *B = LHS_B ? LHS_B : RHS_B;
457 // If we have a negated symbol, then we must have also have a non-negated
458 // symbol in order to encode the expression.
462 Res = MCValue::get(A, B, Result_Cst);
466 bool MCExpr::EvaluateAsRelocatable(MCValue &Res,
467 const MCAsmLayout &Layout) const {
468 return EvaluateAsRelocatableImpl(Res, &Layout.getAssembler(), &Layout,
472 bool MCExpr::EvaluateAsRelocatableImpl(MCValue &Res,
473 const MCAssembler *Asm,
474 const MCAsmLayout *Layout,
475 const SectionAddrMap *Addrs,
477 ++stats::MCExprEvaluate;
481 return cast<MCTargetExpr>(this)->EvaluateAsRelocatableImpl(Res, Layout);
484 Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());
488 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
489 const MCSymbol &Sym = SRE->getSymbol();
491 // Evaluate recursively if this is a variable.
492 if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None) {
493 bool Ret = Sym.getVariableValue()->EvaluateAsRelocatableImpl(Res, Asm,
497 // If we failed to simplify this to a constant, let the target
499 if (Ret && !Res.getSymA() && !Res.getSymB())
503 Res = MCValue::get(SRE, 0, 0);
508 const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);
511 if (!AUE->getSubExpr()->EvaluateAsRelocatableImpl(Value, Asm, Layout,
515 switch (AUE->getOpcode()) {
516 case MCUnaryExpr::LNot:
517 if (!Value.isAbsolute())
519 Res = MCValue::get(!Value.getConstant());
521 case MCUnaryExpr::Minus:
522 /// -(a - b + const) ==> (b - a - const)
523 if (Value.getSymA() && !Value.getSymB())
525 Res = MCValue::get(Value.getSymB(), Value.getSymA(),
526 -Value.getConstant());
528 case MCUnaryExpr::Not:
529 if (!Value.isAbsolute())
531 Res = MCValue::get(~Value.getConstant());
533 case MCUnaryExpr::Plus:
542 const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);
543 MCValue LHSValue, RHSValue;
545 if (!ABE->getLHS()->EvaluateAsRelocatableImpl(LHSValue, Asm, Layout,
547 !ABE->getRHS()->EvaluateAsRelocatableImpl(RHSValue, Asm, Layout,
551 // We only support a few operations on non-constant expressions, handle
553 if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {
554 switch (ABE->getOpcode()) {
557 case MCBinaryExpr::Sub:
558 // Negate RHS and add.
559 return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
560 RHSValue.getSymB(), RHSValue.getSymA(),
561 -RHSValue.getConstant(),
564 case MCBinaryExpr::Add:
565 return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
566 RHSValue.getSymA(), RHSValue.getSymB(),
567 RHSValue.getConstant(),
572 // FIXME: We need target hooks for the evaluation. It may be limited in
573 // width, and gas defines the result of comparisons and right shifts
574 // differently from Apple as.
575 int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();
577 switch (ABE->getOpcode()) {
578 case MCBinaryExpr::Add: Result = LHS + RHS; break;
579 case MCBinaryExpr::And: Result = LHS & RHS; break;
580 case MCBinaryExpr::Div: Result = LHS / RHS; break;
581 case MCBinaryExpr::EQ: Result = LHS == RHS; break;
582 case MCBinaryExpr::GT: Result = LHS > RHS; break;
583 case MCBinaryExpr::GTE: Result = LHS >= RHS; break;
584 case MCBinaryExpr::LAnd: Result = LHS && RHS; break;
585 case MCBinaryExpr::LOr: Result = LHS || RHS; break;
586 case MCBinaryExpr::LT: Result = LHS < RHS; break;
587 case MCBinaryExpr::LTE: Result = LHS <= RHS; break;
588 case MCBinaryExpr::Mod: Result = LHS % RHS; break;
589 case MCBinaryExpr::Mul: Result = LHS * RHS; break;
590 case MCBinaryExpr::NE: Result = LHS != RHS; break;
591 case MCBinaryExpr::Or: Result = LHS | RHS; break;
592 case MCBinaryExpr::Shl: Result = LHS << RHS; break;
593 case MCBinaryExpr::Shr: Result = LHS >> RHS; break;
594 case MCBinaryExpr::Sub: Result = LHS - RHS; break;
595 case MCBinaryExpr::Xor: Result = LHS ^ RHS; break;
598 Res = MCValue::get(Result);
603 llvm_unreachable("Invalid assembly expression kind!");
606 const MCSection *MCExpr::FindAssociatedSection() const {
609 // We never look through target specific expressions.
610 return cast<MCTargetExpr>(this)->FindAssociatedSection();
613 return MCSymbol::AbsolutePseudoSection;
616 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
617 const MCSymbol &Sym = SRE->getSymbol();
620 return &Sym.getSection();
626 return cast<MCUnaryExpr>(this)->getSubExpr()->FindAssociatedSection();
629 const MCBinaryExpr *BE = cast<MCBinaryExpr>(this);
630 const MCSection *LHS_S = BE->getLHS()->FindAssociatedSection();
631 const MCSection *RHS_S = BE->getRHS()->FindAssociatedSection();
633 // If either section is absolute, return the other.
634 if (LHS_S == MCSymbol::AbsolutePseudoSection)
636 if (RHS_S == MCSymbol::AbsolutePseudoSection)
639 // Otherwise, return the first non-null section.
640 return LHS_S ? LHS_S : RHS_S;
644 llvm_unreachable("Invalid assembly expression kind!");