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/MCSymbol.h"
18 #include "llvm/MC/MCValue.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
26 STATISTIC(MCExprEvaluate, "Number of MCExpr evaluations");
30 void MCExpr::print(raw_ostream &OS) const {
33 return cast<MCTargetExpr>(this)->PrintImpl(OS);
34 case MCExpr::Constant:
35 OS << cast<MCConstantExpr>(*this).getValue();
38 case MCExpr::SymbolRef: {
39 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*this);
40 const MCSymbol &Sym = SRE.getSymbol();
41 // Parenthesize names that start with $ so that they don't look like
43 bool UseParens = Sym.getName()[0] == '$';
45 if (SRE.getKind() == MCSymbolRefExpr::VK_PPC_DARWIN_HA16 ||
46 SRE.getKind() == MCSymbolRefExpr::VK_PPC_DARWIN_LO16) {
47 OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
52 OS << '(' << Sym << ')';
56 if (SRE.getKind() == MCSymbolRefExpr::VK_ARM_PLT ||
57 SRE.getKind() == MCSymbolRefExpr::VK_ARM_TLSGD ||
58 SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOT ||
59 SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOTOFF ||
60 SRE.getKind() == MCSymbolRefExpr::VK_ARM_TPOFF ||
61 SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOTTPOFF ||
62 SRE.getKind() == MCSymbolRefExpr::VK_ARM_TARGET1)
63 OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
64 else if (SRE.getKind() != MCSymbolRefExpr::VK_None &&
65 SRE.getKind() != MCSymbolRefExpr::VK_PPC_DARWIN_HA16 &&
66 SRE.getKind() != MCSymbolRefExpr::VK_PPC_DARWIN_LO16)
67 OS << '@' << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
73 const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);
74 switch (UE.getOpcode()) {
75 case MCUnaryExpr::LNot: OS << '!'; break;
76 case MCUnaryExpr::Minus: OS << '-'; break;
77 case MCUnaryExpr::Not: OS << '~'; break;
78 case MCUnaryExpr::Plus: OS << '+'; break;
80 OS << *UE.getSubExpr();
84 case MCExpr::Binary: {
85 const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);
87 // Only print parens around the LHS if it is non-trivial.
88 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS())) {
91 OS << '(' << *BE.getLHS() << ')';
94 switch (BE.getOpcode()) {
95 case MCBinaryExpr::Add:
96 // Print "X-42" instead of "X+-42".
97 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
98 if (RHSC->getValue() < 0) {
99 OS << RHSC->getValue();
106 case MCBinaryExpr::And: OS << '&'; break;
107 case MCBinaryExpr::Div: OS << '/'; break;
108 case MCBinaryExpr::EQ: OS << "=="; break;
109 case MCBinaryExpr::GT: OS << '>'; break;
110 case MCBinaryExpr::GTE: OS << ">="; break;
111 case MCBinaryExpr::LAnd: OS << "&&"; break;
112 case MCBinaryExpr::LOr: OS << "||"; break;
113 case MCBinaryExpr::LT: OS << '<'; break;
114 case MCBinaryExpr::LTE: OS << "<="; break;
115 case MCBinaryExpr::Mod: OS << '%'; break;
116 case MCBinaryExpr::Mul: OS << '*'; break;
117 case MCBinaryExpr::NE: OS << "!="; break;
118 case MCBinaryExpr::Or: OS << '|'; break;
119 case MCBinaryExpr::Shl: OS << "<<"; break;
120 case MCBinaryExpr::Shr: OS << ">>"; break;
121 case MCBinaryExpr::Sub: OS << '-'; break;
122 case MCBinaryExpr::Xor: OS << '^'; break;
125 // Only print parens around the LHS if it is non-trivial.
126 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
129 OS << '(' << *BE.getRHS() << ')';
135 llvm_unreachable("Invalid expression kind!");
138 void MCExpr::dump() const {
145 const MCBinaryExpr *MCBinaryExpr::Create(Opcode Opc, const MCExpr *LHS,
146 const MCExpr *RHS, MCContext &Ctx) {
147 return new (Ctx) MCBinaryExpr(Opc, LHS, RHS);
150 const MCUnaryExpr *MCUnaryExpr::Create(Opcode Opc, const MCExpr *Expr,
152 return new (Ctx) MCUnaryExpr(Opc, Expr);
155 const MCConstantExpr *MCConstantExpr::Create(int64_t Value, MCContext &Ctx) {
156 return new (Ctx) MCConstantExpr(Value);
161 const MCSymbolRefExpr *MCSymbolRefExpr::Create(const MCSymbol *Sym,
164 return new (Ctx) MCSymbolRefExpr(Sym, Kind);
167 const MCSymbolRefExpr *MCSymbolRefExpr::Create(StringRef Name, VariantKind Kind,
169 return Create(Ctx.GetOrCreateSymbol(Name), Kind, Ctx);
172 StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) {
174 case VK_Invalid: return "<<invalid>>";
175 case VK_None: return "<<none>>";
177 case VK_GOT: return "GOT";
178 case VK_GOTOFF: return "GOTOFF";
179 case VK_GOTPCREL: return "GOTPCREL";
180 case VK_GOTTPOFF: return "GOTTPOFF";
181 case VK_INDNTPOFF: return "INDNTPOFF";
182 case VK_NTPOFF: return "NTPOFF";
183 case VK_GOTNTPOFF: return "GOTNTPOFF";
184 case VK_PLT: return "PLT";
185 case VK_TLSGD: return "TLSGD";
186 case VK_TLSLD: return "TLSLD";
187 case VK_TLSLDM: return "TLSLDM";
188 case VK_TPOFF: return "TPOFF";
189 case VK_DTPOFF: return "DTPOFF";
190 case VK_TLVP: return "TLVP";
191 case VK_ARM_PLT: return "(PLT)";
192 case VK_ARM_GOT: return "(GOT)";
193 case VK_ARM_GOTOFF: return "(GOTOFF)";
194 case VK_ARM_TPOFF: return "(tpoff)";
195 case VK_ARM_GOTTPOFF: return "(gottpoff)";
196 case VK_ARM_TLSGD: return "(tlsgd)";
197 case VK_ARM_TARGET1: return "(target1)";
198 case VK_PPC_TOC: return "toc";
199 case VK_PPC_DARWIN_HA16: return "ha16";
200 case VK_PPC_DARWIN_LO16: return "lo16";
201 case VK_PPC_GAS_HA16: return "ha";
202 case VK_PPC_GAS_LO16: return "l";
203 case VK_Mips_GPREL: return "GPREL";
204 case VK_Mips_GOT_CALL: return "GOT_CALL";
205 case VK_Mips_GOT16: return "GOT16";
206 case VK_Mips_GOT: return "GOT";
207 case VK_Mips_ABS_HI: return "ABS_HI";
208 case VK_Mips_ABS_LO: return "ABS_LO";
209 case VK_Mips_TLSGD: return "TLSGD";
210 case VK_Mips_TLSLDM: return "TLSLDM";
211 case VK_Mips_DTPREL_HI: return "DTPREL_HI";
212 case VK_Mips_DTPREL_LO: return "DTPREL_LO";
213 case VK_Mips_GOTTPREL: return "GOTTPREL";
214 case VK_Mips_TPREL_HI: return "TPREL_HI";
215 case VK_Mips_TPREL_LO: return "TPREL_LO";
216 case VK_Mips_GPOFF_HI: return "GPOFF_HI";
217 case VK_Mips_GPOFF_LO: return "GPOFF_LO";
218 case VK_Mips_GOT_DISP: return "GOT_DISP";
219 case VK_Mips_GOT_PAGE: return "GOT_PAGE";
220 case VK_Mips_GOT_OFST: return "GOT_OFST";
222 llvm_unreachable("Invalid variant kind");
225 MCSymbolRefExpr::VariantKind
226 MCSymbolRefExpr::getVariantKindForName(StringRef Name) {
227 return StringSwitch<VariantKind>(Name)
230 .Case("GOTOFF", VK_GOTOFF)
231 .Case("gotoff", VK_GOTOFF)
232 .Case("GOTPCREL", VK_GOTPCREL)
233 .Case("gotpcrel", VK_GOTPCREL)
234 .Case("GOTTPOFF", VK_GOTTPOFF)
235 .Case("gottpoff", VK_GOTTPOFF)
236 .Case("INDNTPOFF", VK_INDNTPOFF)
237 .Case("indntpoff", VK_INDNTPOFF)
238 .Case("NTPOFF", VK_NTPOFF)
239 .Case("ntpoff", VK_NTPOFF)
240 .Case("GOTNTPOFF", VK_GOTNTPOFF)
241 .Case("gotntpoff", VK_GOTNTPOFF)
244 .Case("TLSGD", VK_TLSGD)
245 .Case("tlsgd", VK_TLSGD)
246 .Case("TLSLD", VK_TLSLD)
247 .Case("tlsld", VK_TLSLD)
248 .Case("TLSLDM", VK_TLSLDM)
249 .Case("tlsldm", VK_TLSLDM)
250 .Case("TPOFF", VK_TPOFF)
251 .Case("tpoff", VK_TPOFF)
252 .Case("DTPOFF", VK_DTPOFF)
253 .Case("dtpoff", VK_DTPOFF)
254 .Case("TLVP", VK_TLVP)
255 .Case("tlvp", VK_TLVP)
256 .Default(VK_Invalid);
261 void MCTargetExpr::Anchor() {}
265 bool MCExpr::EvaluateAsAbsolute(int64_t &Res) const {
266 return EvaluateAsAbsolute(Res, 0, 0, 0);
269 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
270 const MCAsmLayout &Layout) const {
271 return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, 0);
274 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
275 const MCAsmLayout &Layout,
276 const SectionAddrMap &Addrs) const {
277 return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, &Addrs);
280 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {
281 return EvaluateAsAbsolute(Res, &Asm, 0, 0);
284 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
285 const MCAsmLayout *Layout,
286 const SectionAddrMap *Addrs) const {
289 // Fast path constants.
290 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {
291 Res = CE->getValue();
295 // FIXME: The use if InSet = Addrs is a hack. Setting InSet causes us
296 // absolutize differences across sections and that is what the MachO writer
299 EvaluateAsRelocatableImpl(Value, Asm, Layout, Addrs, /*InSet*/ Addrs);
301 // Record the current value.
302 Res = Value.getConstant();
304 return IsRelocatable && Value.isAbsolute();
307 /// \brief Helper method for \see EvaluateSymbolAdd().
308 static void AttemptToFoldSymbolOffsetDifference(const MCAssembler *Asm,
309 const MCAsmLayout *Layout,
310 const SectionAddrMap *Addrs,
312 const MCSymbolRefExpr *&A,
313 const MCSymbolRefExpr *&B,
318 const MCSymbol &SA = A->getSymbol();
319 const MCSymbol &SB = B->getSymbol();
321 if (SA.isUndefined() || SB.isUndefined())
324 if (!Asm->getWriter().IsSymbolRefDifferenceFullyResolved(*Asm, A, B, InSet))
327 MCSymbolData &AD = Asm->getSymbolData(SA);
328 MCSymbolData &BD = Asm->getSymbolData(SB);
330 if (AD.getFragment() == BD.getFragment()) {
331 Addend += (AD.getOffset() - BD.getOffset());
333 // Pointers to Thumb symbols need to have their low-bit set to allow
335 if (Asm->isThumbFunc(&SA))
338 // Clear the symbol expr pointers to indicate we have folded these
347 const MCSectionData &SecA = *AD.getFragment()->getParent();
348 const MCSectionData &SecB = *BD.getFragment()->getParent();
350 if ((&SecA != &SecB) && !Addrs)
354 Addend += (Layout->getSymbolOffset(&Asm->getSymbolData(A->getSymbol())) -
355 Layout->getSymbolOffset(&Asm->getSymbolData(B->getSymbol())));
356 if (Addrs && (&SecA != &SecB))
357 Addend += (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
359 // Clear the symbol expr pointers to indicate we have folded these
364 /// \brief Evaluate the result of an add between (conceptually) two MCValues.
366 /// This routine conceptually attempts to construct an MCValue:
367 /// Result = (Result_A - Result_B + Result_Cst)
368 /// from two MCValue's LHS and RHS where
369 /// Result = LHS + RHS
371 /// Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
373 /// This routine attempts to aggresively fold the operands such that the result
374 /// is representable in an MCValue, but may not always succeed.
376 /// \returns True on success, false if the result is not representable in an
379 /// NOTE: It is really important to have both the Asm and Layout arguments.
380 /// They might look redundant, but this function can be used before layout
381 /// is done (see the object streamer for example) and having the Asm argument
382 /// lets us avoid relaxations early.
383 static bool EvaluateSymbolicAdd(const MCAssembler *Asm,
384 const MCAsmLayout *Layout,
385 const SectionAddrMap *Addrs,
387 const MCValue &LHS,const MCSymbolRefExpr *RHS_A,
388 const MCSymbolRefExpr *RHS_B, int64_t RHS_Cst,
390 // FIXME: This routine (and other evaluation parts) are *incredibly* sloppy
391 // about dealing with modifiers. This will ultimately bite us, one day.
392 const MCSymbolRefExpr *LHS_A = LHS.getSymA();
393 const MCSymbolRefExpr *LHS_B = LHS.getSymB();
394 int64_t LHS_Cst = LHS.getConstant();
396 // Fold the result constant immediately.
397 int64_t Result_Cst = LHS_Cst + RHS_Cst;
399 assert((!Layout || Asm) &&
400 "Must have an assembler object if layout is given!");
402 // If we have a layout, we can fold resolved differences.
404 // First, fold out any differences which are fully resolved. By
405 // reassociating terms in
406 // Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
407 // we have the four possible differences:
412 // Since we are attempting to be as aggressive as possible about folding, we
413 // attempt to evaluate each possible alternative.
414 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, LHS_B,
416 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, RHS_B,
418 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, LHS_B,
420 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, RHS_B,
424 // We can't represent the addition or subtraction of two symbols.
425 if ((LHS_A && RHS_A) || (LHS_B && RHS_B))
428 // At this point, we have at most one additive symbol and one subtractive
429 // symbol -- find them.
430 const MCSymbolRefExpr *A = LHS_A ? LHS_A : RHS_A;
431 const MCSymbolRefExpr *B = LHS_B ? LHS_B : RHS_B;
433 // If we have a negated symbol, then we must have also have a non-negated
434 // symbol in order to encode the expression.
438 Res = MCValue::get(A, B, Result_Cst);
442 bool MCExpr::EvaluateAsRelocatable(MCValue &Res,
443 const MCAsmLayout &Layout) const {
444 return EvaluateAsRelocatableImpl(Res, &Layout.getAssembler(), &Layout,
448 bool MCExpr::EvaluateAsRelocatableImpl(MCValue &Res,
449 const MCAssembler *Asm,
450 const MCAsmLayout *Layout,
451 const SectionAddrMap *Addrs,
453 ++stats::MCExprEvaluate;
457 return cast<MCTargetExpr>(this)->EvaluateAsRelocatableImpl(Res, Layout);
460 Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());
464 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
465 const MCSymbol &Sym = SRE->getSymbol();
467 // Evaluate recursively if this is a variable.
468 if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None) {
469 bool Ret = Sym.getVariableValue()->EvaluateAsRelocatableImpl(Res, Asm,
473 // If we failed to simplify this to a constant, let the target
475 if (Ret && !Res.getSymA() && !Res.getSymB())
479 Res = MCValue::get(SRE, 0, 0);
484 const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);
487 if (!AUE->getSubExpr()->EvaluateAsRelocatableImpl(Value, Asm, Layout,
491 switch (AUE->getOpcode()) {
492 case MCUnaryExpr::LNot:
493 if (!Value.isAbsolute())
495 Res = MCValue::get(!Value.getConstant());
497 case MCUnaryExpr::Minus:
498 /// -(a - b + const) ==> (b - a - const)
499 if (Value.getSymA() && !Value.getSymB())
501 Res = MCValue::get(Value.getSymB(), Value.getSymA(),
502 -Value.getConstant());
504 case MCUnaryExpr::Not:
505 if (!Value.isAbsolute())
507 Res = MCValue::get(~Value.getConstant());
509 case MCUnaryExpr::Plus:
518 const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);
519 MCValue LHSValue, RHSValue;
521 if (!ABE->getLHS()->EvaluateAsRelocatableImpl(LHSValue, Asm, Layout,
523 !ABE->getRHS()->EvaluateAsRelocatableImpl(RHSValue, Asm, Layout,
527 // We only support a few operations on non-constant expressions, handle
529 if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {
530 switch (ABE->getOpcode()) {
533 case MCBinaryExpr::Sub:
534 // Negate RHS and add.
535 return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
536 RHSValue.getSymB(), RHSValue.getSymA(),
537 -RHSValue.getConstant(),
540 case MCBinaryExpr::Add:
541 return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
542 RHSValue.getSymA(), RHSValue.getSymB(),
543 RHSValue.getConstant(),
548 // FIXME: We need target hooks for the evaluation. It may be limited in
549 // width, and gas defines the result of comparisons and right shifts
550 // differently from Apple as.
551 int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();
553 switch (ABE->getOpcode()) {
554 case MCBinaryExpr::Add: Result = LHS + RHS; break;
555 case MCBinaryExpr::And: Result = LHS & RHS; break;
556 case MCBinaryExpr::Div: Result = LHS / RHS; break;
557 case MCBinaryExpr::EQ: Result = LHS == RHS; break;
558 case MCBinaryExpr::GT: Result = LHS > RHS; break;
559 case MCBinaryExpr::GTE: Result = LHS >= RHS; break;
560 case MCBinaryExpr::LAnd: Result = LHS && RHS; break;
561 case MCBinaryExpr::LOr: Result = LHS || RHS; break;
562 case MCBinaryExpr::LT: Result = LHS < RHS; break;
563 case MCBinaryExpr::LTE: Result = LHS <= RHS; break;
564 case MCBinaryExpr::Mod: Result = LHS % RHS; break;
565 case MCBinaryExpr::Mul: Result = LHS * RHS; break;
566 case MCBinaryExpr::NE: Result = LHS != RHS; break;
567 case MCBinaryExpr::Or: Result = LHS | RHS; break;
568 case MCBinaryExpr::Shl: Result = LHS << RHS; break;
569 case MCBinaryExpr::Shr: Result = LHS >> RHS; break;
570 case MCBinaryExpr::Sub: Result = LHS - RHS; break;
571 case MCBinaryExpr::Xor: Result = LHS ^ RHS; break;
574 Res = MCValue::get(Result);
579 llvm_unreachable("Invalid assembly expression kind!");
582 const MCSection *MCExpr::FindAssociatedSection() const {
585 // We never look through target specific expressions.
586 return cast<MCTargetExpr>(this)->FindAssociatedSection();
589 return MCSymbol::AbsolutePseudoSection;
592 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
593 const MCSymbol &Sym = SRE->getSymbol();
596 return &Sym.getSection();
602 return cast<MCUnaryExpr>(this)->getSubExpr()->FindAssociatedSection();
605 const MCBinaryExpr *BE = cast<MCBinaryExpr>(this);
606 const MCSection *LHS_S = BE->getLHS()->FindAssociatedSection();
607 const MCSection *RHS_S = BE->getRHS()->FindAssociatedSection();
609 // If either section is absolute, return the other.
610 if (LHS_S == MCSymbol::AbsolutePseudoSection)
612 if (RHS_S == MCSymbol::AbsolutePseudoSection)
615 // Otherwise, return the first non-null section.
616 return LHS_S ? LHS_S : RHS_S;
620 llvm_unreachable("Invalid assembly expression kind!");