[ASan] Make insertion of version mismatch guard configurable
[llvm-core.git] / lib / MC / MCExpr.cpp
blobc4b84a10c0c21bc045f9442bc3b58b7d78a9bc6a
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-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "llvm/MC/MCExpr.h"
10 #include "llvm/ADT/Statistic.h"
11 #include "llvm/ADT/StringExtras.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/Config/llvm-config.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCAsmLayout.h"
17 #include "llvm/MC/MCAssembler.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSymbol.h"
21 #include "llvm/MC/MCValue.h"
22 #include "llvm/Support/Casting.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <cassert>
28 #include <cstdint>
30 using namespace llvm;
32 #define DEBUG_TYPE "mcexpr"
34 namespace {
35 namespace stats {
37 STATISTIC(MCExprEvaluate, "Number of MCExpr evaluations");
39 } // end namespace stats
40 } // end anonymous namespace
42 void MCExpr::print(raw_ostream &OS, const MCAsmInfo *MAI, bool InParens) const {
43 switch (getKind()) {
44 case MCExpr::Target:
45 return cast<MCTargetExpr>(this)->printImpl(OS, MAI);
46 case MCExpr::Constant: {
47 auto Value = cast<MCConstantExpr>(*this).getValue();
48 auto PrintInHex = cast<MCConstantExpr>(*this).useHexFormat();
49 if (PrintInHex)
50 OS << "0x" << Twine::utohexstr(Value);
51 else
52 OS << Value;
53 return;
55 case MCExpr::SymbolRef: {
56 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*this);
57 const MCSymbol &Sym = SRE.getSymbol();
58 // Parenthesize names that start with $ so that they don't look like
59 // absolute names.
60 bool UseParens =
61 !InParens && !Sym.getName().empty() && Sym.getName()[0] == '$';
62 if (UseParens) {
63 OS << '(';
64 Sym.print(OS, MAI);
65 OS << ')';
66 } else
67 Sym.print(OS, MAI);
69 if (SRE.getKind() != MCSymbolRefExpr::VK_None)
70 SRE.printVariantKind(OS);
72 return;
75 case MCExpr::Unary: {
76 const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);
77 switch (UE.getOpcode()) {
78 case MCUnaryExpr::LNot: OS << '!'; break;
79 case MCUnaryExpr::Minus: OS << '-'; break;
80 case MCUnaryExpr::Not: OS << '~'; break;
81 case MCUnaryExpr::Plus: OS << '+'; break;
83 bool Binary = UE.getSubExpr()->getKind() == MCExpr::Binary;
84 if (Binary) OS << "(";
85 UE.getSubExpr()->print(OS, MAI);
86 if (Binary) OS << ")";
87 return;
90 case MCExpr::Binary: {
91 const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);
93 // Only print parens around the LHS if it is non-trivial.
94 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS())) {
95 BE.getLHS()->print(OS, MAI);
96 } else {
97 OS << '(';
98 BE.getLHS()->print(OS, MAI);
99 OS << ')';
102 switch (BE.getOpcode()) {
103 case MCBinaryExpr::Add:
104 // Print "X-42" instead of "X+-42".
105 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
106 if (RHSC->getValue() < 0) {
107 OS << RHSC->getValue();
108 return;
112 OS << '+';
113 break;
114 case MCBinaryExpr::AShr: OS << ">>"; break;
115 case MCBinaryExpr::And: OS << '&'; break;
116 case MCBinaryExpr::Div: OS << '/'; break;
117 case MCBinaryExpr::EQ: OS << "=="; break;
118 case MCBinaryExpr::GT: OS << '>'; break;
119 case MCBinaryExpr::GTE: OS << ">="; break;
120 case MCBinaryExpr::LAnd: OS << "&&"; break;
121 case MCBinaryExpr::LOr: OS << "||"; break;
122 case MCBinaryExpr::LShr: OS << ">>"; break;
123 case MCBinaryExpr::LT: OS << '<'; break;
124 case MCBinaryExpr::LTE: OS << "<="; break;
125 case MCBinaryExpr::Mod: OS << '%'; break;
126 case MCBinaryExpr::Mul: OS << '*'; break;
127 case MCBinaryExpr::NE: OS << "!="; break;
128 case MCBinaryExpr::Or: OS << '|'; break;
129 case MCBinaryExpr::Shl: OS << "<<"; break;
130 case MCBinaryExpr::Sub: OS << '-'; break;
131 case MCBinaryExpr::Xor: OS << '^'; break;
134 // Only print parens around the LHS if it is non-trivial.
135 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
136 BE.getRHS()->print(OS, MAI);
137 } else {
138 OS << '(';
139 BE.getRHS()->print(OS, MAI);
140 OS << ')';
142 return;
146 llvm_unreachable("Invalid expression kind!");
149 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
150 LLVM_DUMP_METHOD void MCExpr::dump() const {
151 dbgs() << *this;
152 dbgs() << '\n';
154 #endif
156 /* *** */
158 const MCBinaryExpr *MCBinaryExpr::create(Opcode Opc, const MCExpr *LHS,
159 const MCExpr *RHS, MCContext &Ctx,
160 SMLoc Loc) {
161 return new (Ctx) MCBinaryExpr(Opc, LHS, RHS, Loc);
164 const MCUnaryExpr *MCUnaryExpr::create(Opcode Opc, const MCExpr *Expr,
165 MCContext &Ctx, SMLoc Loc) {
166 return new (Ctx) MCUnaryExpr(Opc, Expr, Loc);
169 const MCConstantExpr *MCConstantExpr::create(int64_t Value, MCContext &Ctx,
170 bool PrintInHex) {
171 return new (Ctx) MCConstantExpr(Value, PrintInHex);
174 /* *** */
176 MCSymbolRefExpr::MCSymbolRefExpr(const MCSymbol *Symbol, VariantKind Kind,
177 const MCAsmInfo *MAI, SMLoc Loc)
178 : MCExpr(MCExpr::SymbolRef, Loc), Kind(Kind),
179 UseParensForSymbolVariant(MAI->useParensForSymbolVariant()),
180 HasSubsectionsViaSymbols(MAI->hasSubsectionsViaSymbols()),
181 Symbol(Symbol) {
182 assert(Symbol);
185 const MCSymbolRefExpr *MCSymbolRefExpr::create(const MCSymbol *Sym,
186 VariantKind Kind,
187 MCContext &Ctx, SMLoc Loc) {
188 return new (Ctx) MCSymbolRefExpr(Sym, Kind, Ctx.getAsmInfo(), Loc);
191 const MCSymbolRefExpr *MCSymbolRefExpr::create(StringRef Name, VariantKind Kind,
192 MCContext &Ctx) {
193 return create(Ctx.getOrCreateSymbol(Name), Kind, Ctx);
196 StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) {
197 switch (Kind) {
198 case VK_Invalid: return "<<invalid>>";
199 case VK_None: return "<<none>>";
201 case VK_DTPOFF: return "DTPOFF";
202 case VK_DTPREL: return "DTPREL";
203 case VK_GOT: return "GOT";
204 case VK_GOTOFF: return "GOTOFF";
205 case VK_GOTREL: return "GOTREL";
206 case VK_GOTPCREL: return "GOTPCREL";
207 case VK_GOTTPOFF: return "GOTTPOFF";
208 case VK_INDNTPOFF: return "INDNTPOFF";
209 case VK_NTPOFF: return "NTPOFF";
210 case VK_GOTNTPOFF: return "GOTNTPOFF";
211 case VK_PLT: return "PLT";
212 case VK_TLSGD: return "TLSGD";
213 case VK_TLSLD: return "TLSLD";
214 case VK_TLSLDM: return "TLSLDM";
215 case VK_TPOFF: return "TPOFF";
216 case VK_TPREL: return "TPREL";
217 case VK_TLSCALL: return "tlscall";
218 case VK_TLSDESC: return "tlsdesc";
219 case VK_TLVP: return "TLVP";
220 case VK_TLVPPAGE: return "TLVPPAGE";
221 case VK_TLVPPAGEOFF: return "TLVPPAGEOFF";
222 case VK_PAGE: return "PAGE";
223 case VK_PAGEOFF: return "PAGEOFF";
224 case VK_GOTPAGE: return "GOTPAGE";
225 case VK_GOTPAGEOFF: return "GOTPAGEOFF";
226 case VK_SECREL: return "SECREL32";
227 case VK_SIZE: return "SIZE";
228 case VK_WEAKREF: return "WEAKREF";
229 case VK_X86_ABS8: return "ABS8";
230 case VK_ARM_NONE: return "none";
231 case VK_ARM_GOT_PREL: return "GOT_PREL";
232 case VK_ARM_TARGET1: return "target1";
233 case VK_ARM_TARGET2: return "target2";
234 case VK_ARM_PREL31: return "prel31";
235 case VK_ARM_SBREL: return "sbrel";
236 case VK_ARM_TLSLDO: return "tlsldo";
237 case VK_ARM_TLSDESCSEQ: return "tlsdescseq";
238 case VK_AVR_NONE: return "none";
239 case VK_AVR_LO8: return "lo8";
240 case VK_AVR_HI8: return "hi8";
241 case VK_AVR_HLO8: return "hlo8";
242 case VK_AVR_DIFF8: return "diff8";
243 case VK_AVR_DIFF16: return "diff16";
244 case VK_AVR_DIFF32: return "diff32";
245 case VK_PPC_LO: return "l";
246 case VK_PPC_HI: return "h";
247 case VK_PPC_HA: return "ha";
248 case VK_PPC_HIGH: return "high";
249 case VK_PPC_HIGHA: return "higha";
250 case VK_PPC_HIGHER: return "higher";
251 case VK_PPC_HIGHERA: return "highera";
252 case VK_PPC_HIGHEST: return "highest";
253 case VK_PPC_HIGHESTA: return "highesta";
254 case VK_PPC_GOT_LO: return "got@l";
255 case VK_PPC_GOT_HI: return "got@h";
256 case VK_PPC_GOT_HA: return "got@ha";
257 case VK_PPC_TOCBASE: return "tocbase";
258 case VK_PPC_TOC: return "toc";
259 case VK_PPC_TOC_LO: return "toc@l";
260 case VK_PPC_TOC_HI: return "toc@h";
261 case VK_PPC_TOC_HA: return "toc@ha";
262 case VK_PPC_DTPMOD: return "dtpmod";
263 case VK_PPC_TPREL_LO: return "tprel@l";
264 case VK_PPC_TPREL_HI: return "tprel@h";
265 case VK_PPC_TPREL_HA: return "tprel@ha";
266 case VK_PPC_TPREL_HIGH: return "tprel@high";
267 case VK_PPC_TPREL_HIGHA: return "tprel@higha";
268 case VK_PPC_TPREL_HIGHER: return "tprel@higher";
269 case VK_PPC_TPREL_HIGHERA: return "tprel@highera";
270 case VK_PPC_TPREL_HIGHEST: return "tprel@highest";
271 case VK_PPC_TPREL_HIGHESTA: return "tprel@highesta";
272 case VK_PPC_DTPREL_LO: return "dtprel@l";
273 case VK_PPC_DTPREL_HI: return "dtprel@h";
274 case VK_PPC_DTPREL_HA: return "dtprel@ha";
275 case VK_PPC_DTPREL_HIGH: return "dtprel@high";
276 case VK_PPC_DTPREL_HIGHA: return "dtprel@higha";
277 case VK_PPC_DTPREL_HIGHER: return "dtprel@higher";
278 case VK_PPC_DTPREL_HIGHERA: return "dtprel@highera";
279 case VK_PPC_DTPREL_HIGHEST: return "dtprel@highest";
280 case VK_PPC_DTPREL_HIGHESTA: return "dtprel@highesta";
281 case VK_PPC_GOT_TPREL: return "got@tprel";
282 case VK_PPC_GOT_TPREL_LO: return "got@tprel@l";
283 case VK_PPC_GOT_TPREL_HI: return "got@tprel@h";
284 case VK_PPC_GOT_TPREL_HA: return "got@tprel@ha";
285 case VK_PPC_GOT_DTPREL: return "got@dtprel";
286 case VK_PPC_GOT_DTPREL_LO: return "got@dtprel@l";
287 case VK_PPC_GOT_DTPREL_HI: return "got@dtprel@h";
288 case VK_PPC_GOT_DTPREL_HA: return "got@dtprel@ha";
289 case VK_PPC_TLS: return "tls";
290 case VK_PPC_GOT_TLSGD: return "got@tlsgd";
291 case VK_PPC_GOT_TLSGD_LO: return "got@tlsgd@l";
292 case VK_PPC_GOT_TLSGD_HI: return "got@tlsgd@h";
293 case VK_PPC_GOT_TLSGD_HA: return "got@tlsgd@ha";
294 case VK_PPC_TLSGD: return "tlsgd";
295 case VK_PPC_GOT_TLSLD: return "got@tlsld";
296 case VK_PPC_GOT_TLSLD_LO: return "got@tlsld@l";
297 case VK_PPC_GOT_TLSLD_HI: return "got@tlsld@h";
298 case VK_PPC_GOT_TLSLD_HA: return "got@tlsld@ha";
299 case VK_PPC_TLSLD: return "tlsld";
300 case VK_PPC_LOCAL: return "local";
301 case VK_COFF_IMGREL32: return "IMGREL";
302 case VK_Hexagon_PCREL: return "PCREL";
303 case VK_Hexagon_LO16: return "LO16";
304 case VK_Hexagon_HI16: return "HI16";
305 case VK_Hexagon_GPREL: return "GPREL";
306 case VK_Hexagon_GD_GOT: return "GDGOT";
307 case VK_Hexagon_LD_GOT: return "LDGOT";
308 case VK_Hexagon_GD_PLT: return "GDPLT";
309 case VK_Hexagon_LD_PLT: return "LDPLT";
310 case VK_Hexagon_IE: return "IE";
311 case VK_Hexagon_IE_GOT: return "IEGOT";
312 case VK_WASM_TYPEINDEX: return "TYPEINDEX";
313 case VK_WASM_MBREL: return "MBREL";
314 case VK_WASM_TBREL: return "TBREL";
315 case VK_AMDGPU_GOTPCREL32_LO: return "gotpcrel32@lo";
316 case VK_AMDGPU_GOTPCREL32_HI: return "gotpcrel32@hi";
317 case VK_AMDGPU_REL32_LO: return "rel32@lo";
318 case VK_AMDGPU_REL32_HI: return "rel32@hi";
319 case VK_AMDGPU_REL64: return "rel64";
320 case VK_AMDGPU_ABS32_LO: return "abs32@lo";
321 case VK_AMDGPU_ABS32_HI: return "abs32@hi";
323 llvm_unreachable("Invalid variant kind");
326 MCSymbolRefExpr::VariantKind
327 MCSymbolRefExpr::getVariantKindForName(StringRef Name) {
328 return StringSwitch<VariantKind>(Name.lower())
329 .Case("dtprel", VK_DTPREL)
330 .Case("dtpoff", VK_DTPOFF)
331 .Case("got", VK_GOT)
332 .Case("gotoff", VK_GOTOFF)
333 .Case("gotrel", VK_GOTREL)
334 .Case("gotpcrel", VK_GOTPCREL)
335 .Case("gottpoff", VK_GOTTPOFF)
336 .Case("indntpoff", VK_INDNTPOFF)
337 .Case("ntpoff", VK_NTPOFF)
338 .Case("gotntpoff", VK_GOTNTPOFF)
339 .Case("plt", VK_PLT)
340 .Case("tlscall", VK_TLSCALL)
341 .Case("tlsdesc", VK_TLSDESC)
342 .Case("tlsgd", VK_TLSGD)
343 .Case("tlsld", VK_TLSLD)
344 .Case("tlsldm", VK_TLSLDM)
345 .Case("tpoff", VK_TPOFF)
346 .Case("tprel", VK_TPREL)
347 .Case("tlvp", VK_TLVP)
348 .Case("tlvppage", VK_TLVPPAGE)
349 .Case("tlvppageoff", VK_TLVPPAGEOFF)
350 .Case("page", VK_PAGE)
351 .Case("pageoff", VK_PAGEOFF)
352 .Case("gotpage", VK_GOTPAGE)
353 .Case("gotpageoff", VK_GOTPAGEOFF)
354 .Case("imgrel", VK_COFF_IMGREL32)
355 .Case("secrel32", VK_SECREL)
356 .Case("size", VK_SIZE)
357 .Case("abs8", VK_X86_ABS8)
358 .Case("l", VK_PPC_LO)
359 .Case("h", VK_PPC_HI)
360 .Case("ha", VK_PPC_HA)
361 .Case("high", VK_PPC_HIGH)
362 .Case("higha", VK_PPC_HIGHA)
363 .Case("higher", VK_PPC_HIGHER)
364 .Case("highera", VK_PPC_HIGHERA)
365 .Case("highest", VK_PPC_HIGHEST)
366 .Case("highesta", VK_PPC_HIGHESTA)
367 .Case("got@l", VK_PPC_GOT_LO)
368 .Case("got@h", VK_PPC_GOT_HI)
369 .Case("got@ha", VK_PPC_GOT_HA)
370 .Case("local", VK_PPC_LOCAL)
371 .Case("tocbase", VK_PPC_TOCBASE)
372 .Case("toc", VK_PPC_TOC)
373 .Case("toc@l", VK_PPC_TOC_LO)
374 .Case("toc@h", VK_PPC_TOC_HI)
375 .Case("toc@ha", VK_PPC_TOC_HA)
376 .Case("tls", VK_PPC_TLS)
377 .Case("dtpmod", VK_PPC_DTPMOD)
378 .Case("tprel@l", VK_PPC_TPREL_LO)
379 .Case("tprel@h", VK_PPC_TPREL_HI)
380 .Case("tprel@ha", VK_PPC_TPREL_HA)
381 .Case("tprel@high", VK_PPC_TPREL_HIGH)
382 .Case("tprel@higha", VK_PPC_TPREL_HIGHA)
383 .Case("tprel@higher", VK_PPC_TPREL_HIGHER)
384 .Case("tprel@highera", VK_PPC_TPREL_HIGHERA)
385 .Case("tprel@highest", VK_PPC_TPREL_HIGHEST)
386 .Case("tprel@highesta", VK_PPC_TPREL_HIGHESTA)
387 .Case("dtprel@l", VK_PPC_DTPREL_LO)
388 .Case("dtprel@h", VK_PPC_DTPREL_HI)
389 .Case("dtprel@ha", VK_PPC_DTPREL_HA)
390 .Case("dtprel@high", VK_PPC_DTPREL_HIGH)
391 .Case("dtprel@higha", VK_PPC_DTPREL_HIGHA)
392 .Case("dtprel@higher", VK_PPC_DTPREL_HIGHER)
393 .Case("dtprel@highera", VK_PPC_DTPREL_HIGHERA)
394 .Case("dtprel@highest", VK_PPC_DTPREL_HIGHEST)
395 .Case("dtprel@highesta", VK_PPC_DTPREL_HIGHESTA)
396 .Case("got@tprel", VK_PPC_GOT_TPREL)
397 .Case("got@tprel@l", VK_PPC_GOT_TPREL_LO)
398 .Case("got@tprel@h", VK_PPC_GOT_TPREL_HI)
399 .Case("got@tprel@ha", VK_PPC_GOT_TPREL_HA)
400 .Case("got@dtprel", VK_PPC_GOT_DTPREL)
401 .Case("got@dtprel@l", VK_PPC_GOT_DTPREL_LO)
402 .Case("got@dtprel@h", VK_PPC_GOT_DTPREL_HI)
403 .Case("got@dtprel@ha", VK_PPC_GOT_DTPREL_HA)
404 .Case("got@tlsgd", VK_PPC_GOT_TLSGD)
405 .Case("got@tlsgd@l", VK_PPC_GOT_TLSGD_LO)
406 .Case("got@tlsgd@h", VK_PPC_GOT_TLSGD_HI)
407 .Case("got@tlsgd@ha", VK_PPC_GOT_TLSGD_HA)
408 .Case("got@tlsld", VK_PPC_GOT_TLSLD)
409 .Case("got@tlsld@l", VK_PPC_GOT_TLSLD_LO)
410 .Case("got@tlsld@h", VK_PPC_GOT_TLSLD_HI)
411 .Case("got@tlsld@ha", VK_PPC_GOT_TLSLD_HA)
412 .Case("gdgot", VK_Hexagon_GD_GOT)
413 .Case("gdplt", VK_Hexagon_GD_PLT)
414 .Case("iegot", VK_Hexagon_IE_GOT)
415 .Case("ie", VK_Hexagon_IE)
416 .Case("ldgot", VK_Hexagon_LD_GOT)
417 .Case("ldplt", VK_Hexagon_LD_PLT)
418 .Case("pcrel", VK_Hexagon_PCREL)
419 .Case("none", VK_ARM_NONE)
420 .Case("got_prel", VK_ARM_GOT_PREL)
421 .Case("target1", VK_ARM_TARGET1)
422 .Case("target2", VK_ARM_TARGET2)
423 .Case("prel31", VK_ARM_PREL31)
424 .Case("sbrel", VK_ARM_SBREL)
425 .Case("tlsldo", VK_ARM_TLSLDO)
426 .Case("lo8", VK_AVR_LO8)
427 .Case("hi8", VK_AVR_HI8)
428 .Case("hlo8", VK_AVR_HLO8)
429 .Case("typeindex", VK_WASM_TYPEINDEX)
430 .Case("tbrel", VK_WASM_TBREL)
431 .Case("mbrel", VK_WASM_MBREL)
432 .Case("gotpcrel32@lo", VK_AMDGPU_GOTPCREL32_LO)
433 .Case("gotpcrel32@hi", VK_AMDGPU_GOTPCREL32_HI)
434 .Case("rel32@lo", VK_AMDGPU_REL32_LO)
435 .Case("rel32@hi", VK_AMDGPU_REL32_HI)
436 .Case("rel64", VK_AMDGPU_REL64)
437 .Case("abs32@lo", VK_AMDGPU_ABS32_LO)
438 .Case("abs32@hi", VK_AMDGPU_ABS32_HI)
439 .Default(VK_Invalid);
442 void MCSymbolRefExpr::printVariantKind(raw_ostream &OS) const {
443 if (UseParensForSymbolVariant)
444 OS << '(' << MCSymbolRefExpr::getVariantKindName(getKind()) << ')';
445 else
446 OS << '@' << MCSymbolRefExpr::getVariantKindName(getKind());
449 /* *** */
451 void MCTargetExpr::anchor() {}
453 /* *** */
455 bool MCExpr::evaluateAsAbsolute(int64_t &Res) const {
456 return evaluateAsAbsolute(Res, nullptr, nullptr, nullptr, false);
459 bool MCExpr::evaluateAsAbsolute(int64_t &Res,
460 const MCAsmLayout &Layout) const {
461 return evaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, nullptr, false);
464 bool MCExpr::evaluateAsAbsolute(int64_t &Res,
465 const MCAsmLayout &Layout,
466 const SectionAddrMap &Addrs) const {
467 // Setting InSet causes us to absolutize differences across sections and that
468 // is what the MachO writer uses Addrs for.
469 return evaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, &Addrs, true);
472 bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {
473 return evaluateAsAbsolute(Res, &Asm, nullptr, nullptr, false);
476 bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm) const {
477 return evaluateAsAbsolute(Res, Asm, nullptr, nullptr, false);
480 bool MCExpr::evaluateKnownAbsolute(int64_t &Res,
481 const MCAsmLayout &Layout) const {
482 return evaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, nullptr,
483 true);
486 bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
487 const MCAsmLayout *Layout,
488 const SectionAddrMap *Addrs, bool InSet) const {
489 MCValue Value;
491 // Fast path constants.
492 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {
493 Res = CE->getValue();
494 return true;
497 bool IsRelocatable =
498 evaluateAsRelocatableImpl(Value, Asm, Layout, nullptr, Addrs, InSet);
500 // Record the current value.
501 Res = Value.getConstant();
503 return IsRelocatable && Value.isAbsolute();
506 /// Helper method for \see EvaluateSymbolAdd().
507 static void AttemptToFoldSymbolOffsetDifference(
508 const MCAssembler *Asm, const MCAsmLayout *Layout,
509 const SectionAddrMap *Addrs, bool InSet, const MCSymbolRefExpr *&A,
510 const MCSymbolRefExpr *&B, int64_t &Addend) {
511 if (!A || !B)
512 return;
514 const MCSymbol &SA = A->getSymbol();
515 const MCSymbol &SB = B->getSymbol();
517 if (SA.isUndefined() || SB.isUndefined())
518 return;
520 if (!Asm->getWriter().isSymbolRefDifferenceFullyResolved(*Asm, A, B, InSet))
521 return;
523 if (SA.getFragment() == SB.getFragment() && !SA.isVariable() &&
524 !SA.isUnset() && !SB.isVariable() && !SB.isUnset()) {
525 Addend += (SA.getOffset() - SB.getOffset());
527 // Pointers to Thumb symbols need to have their low-bit set to allow
528 // for interworking.
529 if (Asm->isThumbFunc(&SA))
530 Addend |= 1;
532 // If symbol is labeled as micromips, we set low-bit to ensure
533 // correct offset in .gcc_except_table
534 if (Asm->getBackend().isMicroMips(&SA))
535 Addend |= 1;
537 // Clear the symbol expr pointers to indicate we have folded these
538 // operands.
539 A = B = nullptr;
540 return;
543 if (!Layout)
544 return;
546 const MCSection &SecA = *SA.getFragment()->getParent();
547 const MCSection &SecB = *SB.getFragment()->getParent();
549 if ((&SecA != &SecB) && !Addrs)
550 return;
552 // Eagerly evaluate.
553 Addend += Layout->getSymbolOffset(A->getSymbol()) -
554 Layout->getSymbolOffset(B->getSymbol());
555 if (Addrs && (&SecA != &SecB))
556 Addend += (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
558 // Pointers to Thumb symbols need to have their low-bit set to allow
559 // for interworking.
560 if (Asm->isThumbFunc(&SA))
561 Addend |= 1;
563 // If symbol is labeled as micromips, we set low-bit to ensure
564 // correct offset in .gcc_except_table
565 if (Asm->getBackend().isMicroMips(&SA))
566 Addend |= 1;
568 // Clear the symbol expr pointers to indicate we have folded these
569 // operands.
570 A = B = nullptr;
573 static bool canFold(const MCAssembler *Asm, const MCSymbolRefExpr *A,
574 const MCSymbolRefExpr *B, bool InSet) {
575 if (InSet)
576 return true;
578 if (!Asm->getBackend().requiresDiffExpressionRelocations())
579 return true;
581 const MCSymbol &CheckSym = A ? A->getSymbol() : B->getSymbol();
582 if (!CheckSym.isInSection())
583 return true;
585 if (!CheckSym.getSection().hasInstructions())
586 return true;
588 return false;
591 /// Evaluate the result of an add between (conceptually) two MCValues.
593 /// This routine conceptually attempts to construct an MCValue:
594 /// Result = (Result_A - Result_B + Result_Cst)
595 /// from two MCValue's LHS and RHS where
596 /// Result = LHS + RHS
597 /// and
598 /// Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
600 /// This routine attempts to aggresively fold the operands such that the result
601 /// is representable in an MCValue, but may not always succeed.
603 /// \returns True on success, false if the result is not representable in an
604 /// MCValue.
606 /// NOTE: It is really important to have both the Asm and Layout arguments.
607 /// They might look redundant, but this function can be used before layout
608 /// is done (see the object streamer for example) and having the Asm argument
609 /// lets us avoid relaxations early.
610 static bool
611 EvaluateSymbolicAdd(const MCAssembler *Asm, const MCAsmLayout *Layout,
612 const SectionAddrMap *Addrs, bool InSet, const MCValue &LHS,
613 const MCSymbolRefExpr *RHS_A, const MCSymbolRefExpr *RHS_B,
614 int64_t RHS_Cst, MCValue &Res) {
615 // FIXME: This routine (and other evaluation parts) are *incredibly* sloppy
616 // about dealing with modifiers. This will ultimately bite us, one day.
617 const MCSymbolRefExpr *LHS_A = LHS.getSymA();
618 const MCSymbolRefExpr *LHS_B = LHS.getSymB();
619 int64_t LHS_Cst = LHS.getConstant();
621 // Fold the result constant immediately.
622 int64_t Result_Cst = LHS_Cst + RHS_Cst;
624 assert((!Layout || Asm) &&
625 "Must have an assembler object if layout is given!");
627 // If we have a layout, we can fold resolved differences. Do not do this if
628 // the backend requires this to be emitted as individual relocations, unless
629 // the InSet flag is set to get the current difference anyway (used for
630 // example to calculate symbol sizes).
631 if (Asm && canFold(Asm, LHS_A, LHS_B, InSet)) {
632 // First, fold out any differences which are fully resolved. By
633 // reassociating terms in
634 // Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
635 // we have the four possible differences:
636 // (LHS_A - LHS_B),
637 // (LHS_A - RHS_B),
638 // (RHS_A - LHS_B),
639 // (RHS_A - RHS_B).
640 // Since we are attempting to be as aggressive as possible about folding, we
641 // attempt to evaluate each possible alternative.
642 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, LHS_B,
643 Result_Cst);
644 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, RHS_B,
645 Result_Cst);
646 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, LHS_B,
647 Result_Cst);
648 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, RHS_B,
649 Result_Cst);
652 // We can't represent the addition or subtraction of two symbols.
653 if ((LHS_A && RHS_A) || (LHS_B && RHS_B))
654 return false;
656 // At this point, we have at most one additive symbol and one subtractive
657 // symbol -- find them.
658 const MCSymbolRefExpr *A = LHS_A ? LHS_A : RHS_A;
659 const MCSymbolRefExpr *B = LHS_B ? LHS_B : RHS_B;
661 Res = MCValue::get(A, B, Result_Cst);
662 return true;
665 bool MCExpr::evaluateAsRelocatable(MCValue &Res,
666 const MCAsmLayout *Layout,
667 const MCFixup *Fixup) const {
668 MCAssembler *Assembler = Layout ? &Layout->getAssembler() : nullptr;
669 return evaluateAsRelocatableImpl(Res, Assembler, Layout, Fixup, nullptr,
670 false);
673 bool MCExpr::evaluateAsValue(MCValue &Res, const MCAsmLayout &Layout) const {
674 MCAssembler *Assembler = &Layout.getAssembler();
675 return evaluateAsRelocatableImpl(Res, Assembler, &Layout, nullptr, nullptr,
676 true);
679 static bool canExpand(const MCSymbol &Sym, bool InSet) {
680 const MCExpr *Expr = Sym.getVariableValue();
681 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
682 if (Inner) {
683 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
684 return false;
687 if (InSet)
688 return true;
689 return !Sym.isInSection();
692 bool MCExpr::evaluateAsRelocatableImpl(MCValue &Res, const MCAssembler *Asm,
693 const MCAsmLayout *Layout,
694 const MCFixup *Fixup,
695 const SectionAddrMap *Addrs,
696 bool InSet) const {
697 ++stats::MCExprEvaluate;
699 switch (getKind()) {
700 case Target:
701 return cast<MCTargetExpr>(this)->evaluateAsRelocatableImpl(Res, Layout,
702 Fixup);
704 case Constant:
705 Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());
706 return true;
708 case SymbolRef: {
709 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
710 const MCSymbol &Sym = SRE->getSymbol();
712 // Evaluate recursively if this is a variable.
713 if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None &&
714 canExpand(Sym, InSet)) {
715 bool IsMachO = SRE->hasSubsectionsViaSymbols();
716 if (Sym.getVariableValue()->evaluateAsRelocatableImpl(
717 Res, Asm, Layout, Fixup, Addrs, InSet || IsMachO)) {
718 if (!IsMachO)
719 return true;
721 const MCSymbolRefExpr *A = Res.getSymA();
722 const MCSymbolRefExpr *B = Res.getSymB();
723 // FIXME: This is small hack. Given
724 // a = b + 4
725 // .long a
726 // the OS X assembler will completely drop the 4. We should probably
727 // include it in the relocation or produce an error if that is not
728 // possible.
729 // Allow constant expressions.
730 if (!A && !B)
731 return true;
732 // Allows aliases with zero offset.
733 if (Res.getConstant() == 0 && (!A || !B))
734 return true;
738 Res = MCValue::get(SRE, nullptr, 0);
739 return true;
742 case Unary: {
743 const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);
744 MCValue Value;
746 if (!AUE->getSubExpr()->evaluateAsRelocatableImpl(Value, Asm, Layout, Fixup,
747 Addrs, InSet))
748 return false;
750 switch (AUE->getOpcode()) {
751 case MCUnaryExpr::LNot:
752 if (!Value.isAbsolute())
753 return false;
754 Res = MCValue::get(!Value.getConstant());
755 break;
756 case MCUnaryExpr::Minus:
757 /// -(a - b + const) ==> (b - a - const)
758 if (Value.getSymA() && !Value.getSymB())
759 return false;
761 // The cast avoids undefined behavior if the constant is INT64_MIN.
762 Res = MCValue::get(Value.getSymB(), Value.getSymA(),
763 -(uint64_t)Value.getConstant());
764 break;
765 case MCUnaryExpr::Not:
766 if (!Value.isAbsolute())
767 return false;
768 Res = MCValue::get(~Value.getConstant());
769 break;
770 case MCUnaryExpr::Plus:
771 Res = Value;
772 break;
775 return true;
778 case Binary: {
779 const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);
780 MCValue LHSValue, RHSValue;
782 if (!ABE->getLHS()->evaluateAsRelocatableImpl(LHSValue, Asm, Layout, Fixup,
783 Addrs, InSet) ||
784 !ABE->getRHS()->evaluateAsRelocatableImpl(RHSValue, Asm, Layout, Fixup,
785 Addrs, InSet)) {
786 // Check if both are Target Expressions, see if we can compare them.
787 if (const MCTargetExpr *L = dyn_cast<MCTargetExpr>(ABE->getLHS()))
788 if (const MCTargetExpr *R = cast<MCTargetExpr>(ABE->getRHS())) {
789 switch (ABE->getOpcode()) {
790 case MCBinaryExpr::EQ:
791 Res = MCValue::get((L->isEqualTo(R)) ? -1 : 0);
792 return true;
793 case MCBinaryExpr::NE:
794 Res = MCValue::get((R->isEqualTo(R)) ? 0 : -1);
795 return true;
796 default: break;
799 return false;
802 // We only support a few operations on non-constant expressions, handle
803 // those first.
804 if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {
805 switch (ABE->getOpcode()) {
806 default:
807 return false;
808 case MCBinaryExpr::Sub:
809 // Negate RHS and add.
810 // The cast avoids undefined behavior if the constant is INT64_MIN.
811 return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
812 RHSValue.getSymB(), RHSValue.getSymA(),
813 -(uint64_t)RHSValue.getConstant(), Res);
815 case MCBinaryExpr::Add:
816 return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
817 RHSValue.getSymA(), RHSValue.getSymB(),
818 RHSValue.getConstant(), Res);
822 // FIXME: We need target hooks for the evaluation. It may be limited in
823 // width, and gas defines the result of comparisons differently from
824 // Apple as.
825 int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();
826 int64_t Result = 0;
827 auto Op = ABE->getOpcode();
828 switch (Op) {
829 case MCBinaryExpr::AShr: Result = LHS >> RHS; break;
830 case MCBinaryExpr::Add: Result = LHS + RHS; break;
831 case MCBinaryExpr::And: Result = LHS & RHS; break;
832 case MCBinaryExpr::Div:
833 case MCBinaryExpr::Mod:
834 // Handle division by zero. gas just emits a warning and keeps going,
835 // we try to be stricter.
836 // FIXME: Currently the caller of this function has no way to understand
837 // we're bailing out because of 'division by zero'. Therefore, it will
838 // emit a 'expected relocatable expression' error. It would be nice to
839 // change this code to emit a better diagnostic.
840 if (RHS == 0)
841 return false;
842 if (ABE->getOpcode() == MCBinaryExpr::Div)
843 Result = LHS / RHS;
844 else
845 Result = LHS % RHS;
846 break;
847 case MCBinaryExpr::EQ: Result = LHS == RHS; break;
848 case MCBinaryExpr::GT: Result = LHS > RHS; break;
849 case MCBinaryExpr::GTE: Result = LHS >= RHS; break;
850 case MCBinaryExpr::LAnd: Result = LHS && RHS; break;
851 case MCBinaryExpr::LOr: Result = LHS || RHS; break;
852 case MCBinaryExpr::LShr: Result = uint64_t(LHS) >> uint64_t(RHS); break;
853 case MCBinaryExpr::LT: Result = LHS < RHS; break;
854 case MCBinaryExpr::LTE: Result = LHS <= RHS; break;
855 case MCBinaryExpr::Mul: Result = LHS * RHS; break;
856 case MCBinaryExpr::NE: Result = LHS != RHS; break;
857 case MCBinaryExpr::Or: Result = LHS | RHS; break;
858 case MCBinaryExpr::Shl: Result = uint64_t(LHS) << uint64_t(RHS); break;
859 case MCBinaryExpr::Sub: Result = LHS - RHS; break;
860 case MCBinaryExpr::Xor: Result = LHS ^ RHS; break;
863 switch (Op) {
864 default:
865 Res = MCValue::get(Result);
866 break;
867 case MCBinaryExpr::EQ:
868 case MCBinaryExpr::GT:
869 case MCBinaryExpr::GTE:
870 case MCBinaryExpr::LT:
871 case MCBinaryExpr::LTE:
872 case MCBinaryExpr::NE:
873 // A comparison operator returns a -1 if true and 0 if false.
874 Res = MCValue::get(Result ? -1 : 0);
875 break;
878 return true;
882 llvm_unreachable("Invalid assembly expression kind!");
885 MCFragment *MCExpr::findAssociatedFragment() const {
886 switch (getKind()) {
887 case Target:
888 // We never look through target specific expressions.
889 return cast<MCTargetExpr>(this)->findAssociatedFragment();
891 case Constant:
892 return MCSymbol::AbsolutePseudoFragment;
894 case SymbolRef: {
895 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
896 const MCSymbol &Sym = SRE->getSymbol();
897 return Sym.getFragment();
900 case Unary:
901 return cast<MCUnaryExpr>(this)->getSubExpr()->findAssociatedFragment();
903 case Binary: {
904 const MCBinaryExpr *BE = cast<MCBinaryExpr>(this);
905 MCFragment *LHS_F = BE->getLHS()->findAssociatedFragment();
906 MCFragment *RHS_F = BE->getRHS()->findAssociatedFragment();
908 // If either is absolute, return the other.
909 if (LHS_F == MCSymbol::AbsolutePseudoFragment)
910 return RHS_F;
911 if (RHS_F == MCSymbol::AbsolutePseudoFragment)
912 return LHS_F;
914 // Not always correct, but probably the best we can do without more context.
915 if (BE->getOpcode() == MCBinaryExpr::Sub)
916 return MCSymbol::AbsolutePseudoFragment;
918 // Otherwise, return the first non-null fragment.
919 return LHS_F ? LHS_F : RHS_F;
923 llvm_unreachable("Invalid assembly expression kind!");