ARM/ISel: Factor out isScaledConstantInRange() helper.
[oota-llvm.git] / lib / MC / MCExpr.cpp
1 //===- MCExpr.cpp - Assembly Level Expression Implementation --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #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/raw_ostream.h"
21 #include "llvm/Target/TargetAsmBackend.h"
22 using namespace llvm;
23
24 namespace {
25 namespace stats {
26 STATISTIC(MCExprEvaluate, "Number of MCExpr evaluations");
27 }
28 }
29
30 void MCExpr::print(raw_ostream &OS) const {
31   switch (getKind()) {
32   case MCExpr::Target:
33     return cast<MCTargetExpr>(this)->PrintImpl(OS);
34   case MCExpr::Constant:
35     OS << cast<MCConstantExpr>(*this).getValue();
36     return;
37
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
42     // absolute names.
43     bool UseParens = Sym.getName()[0] == '$';
44
45     if (SRE.getKind() == MCSymbolRefExpr::VK_PPC_HA16 ||
46         SRE.getKind() == MCSymbolRefExpr::VK_PPC_LO16) {
47       OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
48       UseParens = true;
49     }
50
51     if (UseParens)
52       OS << '(' << Sym << ')';
53     else
54       OS << Sym;
55
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       OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
63     else if (SRE.getKind() != MCSymbolRefExpr::VK_None &&
64              SRE.getKind() != MCSymbolRefExpr::VK_PPC_HA16 &&
65              SRE.getKind() != MCSymbolRefExpr::VK_PPC_LO16)
66       OS << '@' << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
67
68     return;
69   }
70
71   case MCExpr::Unary: {
72     const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);
73     switch (UE.getOpcode()) {
74     default: assert(0 && "Invalid opcode!");
75     case MCUnaryExpr::LNot:  OS << '!'; break;
76     case MCUnaryExpr::Minus: OS << '-'; break;
77     case MCUnaryExpr::Not:   OS << '~'; break;
78     case MCUnaryExpr::Plus:  OS << '+'; break;
79     }
80     OS << *UE.getSubExpr();
81     return;
82   }
83
84   case MCExpr::Binary: {
85     const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);
86
87     // Only print parens around the LHS if it is non-trivial.
88     if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS())) {
89       OS << *BE.getLHS();
90     } else {
91       OS << '(' << *BE.getLHS() << ')';
92     }
93
94     switch (BE.getOpcode()) {
95     default: assert(0 && "Invalid opcode!");
96     case MCBinaryExpr::Add:
97       // Print "X-42" instead of "X+-42".
98       if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
99         if (RHSC->getValue() < 0) {
100           OS << RHSC->getValue();
101           return;
102         }
103       }
104
105       OS <<  '+';
106       break;
107     case MCBinaryExpr::And:  OS <<  '&'; break;
108     case MCBinaryExpr::Div:  OS <<  '/'; break;
109     case MCBinaryExpr::EQ:   OS << "=="; break;
110     case MCBinaryExpr::GT:   OS <<  '>'; break;
111     case MCBinaryExpr::GTE:  OS << ">="; break;
112     case MCBinaryExpr::LAnd: OS << "&&"; break;
113     case MCBinaryExpr::LOr:  OS << "||"; break;
114     case MCBinaryExpr::LT:   OS <<  '<'; break;
115     case MCBinaryExpr::LTE:  OS << "<="; break;
116     case MCBinaryExpr::Mod:  OS <<  '%'; break;
117     case MCBinaryExpr::Mul:  OS <<  '*'; break;
118     case MCBinaryExpr::NE:   OS << "!="; break;
119     case MCBinaryExpr::Or:   OS <<  '|'; break;
120     case MCBinaryExpr::Shl:  OS << "<<"; break;
121     case MCBinaryExpr::Shr:  OS << ">>"; break;
122     case MCBinaryExpr::Sub:  OS <<  '-'; break;
123     case MCBinaryExpr::Xor:  OS <<  '^'; break;
124     }
125
126     // Only print parens around the LHS if it is non-trivial.
127     if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
128       OS << *BE.getRHS();
129     } else {
130       OS << '(' << *BE.getRHS() << ')';
131     }
132     return;
133   }
134   }
135
136   assert(0 && "Invalid expression kind!");
137 }
138
139 void MCExpr::dump() const {
140   print(dbgs());
141   dbgs() << '\n';
142 }
143
144 /* *** */
145
146 const MCBinaryExpr *MCBinaryExpr::Create(Opcode Opc, const MCExpr *LHS,
147                                          const MCExpr *RHS, MCContext &Ctx) {
148   return new (Ctx) MCBinaryExpr(Opc, LHS, RHS);
149 }
150
151 const MCUnaryExpr *MCUnaryExpr::Create(Opcode Opc, const MCExpr *Expr,
152                                        MCContext &Ctx) {
153   return new (Ctx) MCUnaryExpr(Opc, Expr);
154 }
155
156 const MCConstantExpr *MCConstantExpr::Create(int64_t Value, MCContext &Ctx) {
157   return new (Ctx) MCConstantExpr(Value);
158 }
159
160 /* *** */
161
162 const MCSymbolRefExpr *MCSymbolRefExpr::Create(const MCSymbol *Sym,
163                                                VariantKind Kind,
164                                                MCContext &Ctx) {
165   return new (Ctx) MCSymbolRefExpr(Sym, Kind);
166 }
167
168 const MCSymbolRefExpr *MCSymbolRefExpr::Create(StringRef Name, VariantKind Kind,
169                                                MCContext &Ctx) {
170   return Create(Ctx.GetOrCreateSymbol(Name), Kind, Ctx);
171 }
172
173 StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) {
174   switch (Kind) {
175   default:
176   case VK_Invalid: return "<<invalid>>";
177   case VK_None: return "<<none>>";
178
179   case VK_GOT: return "GOT";
180   case VK_GOTOFF: return "GOTOFF";
181   case VK_GOTPCREL: return "GOTPCREL";
182   case VK_GOTTPOFF: return "GOTTPOFF";
183   case VK_INDNTPOFF: return "INDNTPOFF";
184   case VK_NTPOFF: return "NTPOFF";
185   case VK_GOTNTPOFF: return "GOTNTPOFF";
186   case VK_PLT: return "PLT";
187   case VK_TLSGD: return "TLSGD";
188   case VK_TLSLD: return "TLSLD";
189   case VK_TLSLDM: return "TLSLDM";
190   case VK_TPOFF: return "TPOFF";
191   case VK_DTPOFF: return "DTPOFF";
192   case VK_TLVP: return "TLVP";
193   case VK_ARM_PLT: return "(PLT)";
194   case VK_ARM_GOT: return "(GOT)";
195   case VK_ARM_GOTOFF: return "(GOTOFF)";
196   case VK_ARM_TPOFF: return "(tpoff)";
197   case VK_ARM_GOTTPOFF: return "(gottpoff)";
198   case VK_ARM_TLSGD: return "(tlsgd)";
199   case VK_PPC_TOC: return "toc";
200   case VK_PPC_HA16: return "ha16";
201   case VK_PPC_LO16: return "lo16";
202   }
203 }
204
205 MCSymbolRefExpr::VariantKind
206 MCSymbolRefExpr::getVariantKindForName(StringRef Name) {
207   return StringSwitch<VariantKind>(Name)
208     .Case("GOT", VK_GOT)
209     .Case("GOTOFF", VK_GOTOFF)
210     .Case("GOTPCREL", VK_GOTPCREL)
211     .Case("GOTTPOFF", VK_GOTTPOFF)
212     .Case("INDNTPOFF", VK_INDNTPOFF)
213     .Case("NTPOFF", VK_NTPOFF)
214     .Case("GOTNTPOFF", VK_GOTNTPOFF)
215     .Case("PLT", VK_PLT)
216     .Case("TLSGD", VK_TLSGD)
217     .Case("TLSLD", VK_TLSLD)
218     .Case("TLSLDM", VK_TLSLDM)
219     .Case("TPOFF", VK_TPOFF)
220     .Case("DTPOFF", VK_DTPOFF)
221     .Case("TLVP", VK_TLVP)
222     .Default(VK_Invalid);
223 }
224
225 /* *** */
226
227 void MCTargetExpr::Anchor() {}
228
229 /* *** */
230
231 bool MCExpr::EvaluateAsAbsolute(int64_t &Res) const {
232   return EvaluateAsAbsolute(Res, 0, 0, 0);
233 }
234
235 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
236                                 const MCAsmLayout &Layout) const {
237   return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, 0);
238 }
239
240 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
241                                 const MCAsmLayout &Layout,
242                                 const SectionAddrMap &Addrs) const {
243   return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, &Addrs);
244 }
245
246 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {
247   return EvaluateAsAbsolute(Res, &Asm, 0, 0);
248 }
249
250 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
251                                 const MCAsmLayout *Layout,
252                                 const SectionAddrMap *Addrs) const {
253   MCValue Value;
254
255   // Fast path constants.
256   if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {
257     Res = CE->getValue();
258     return true;
259   }
260
261   // FIXME: The use if InSet = Addrs is a hack. Setting InSet causes us
262   // absolutize differences across sections and that is what the MachO writer
263   // uses Addrs for.
264   bool IsRelocatable =
265     EvaluateAsRelocatableImpl(Value, Asm, Layout, Addrs, /*InSet*/ Addrs);
266
267   // Record the current value.
268   Res = Value.getConstant();
269
270   return IsRelocatable && Value.isAbsolute();
271 }
272
273 /// \brief Helper method for \see EvaluateSymbolAdd().
274 static void AttemptToFoldSymbolOffsetDifference(const MCAssembler *Asm,
275                                                 const MCAsmLayout *Layout,
276                                                 const SectionAddrMap *Addrs,
277                                                 bool InSet,
278                                                 const MCSymbolRefExpr *&A,
279                                                 const MCSymbolRefExpr *&B,
280                                                 int64_t &Addend) {
281   if (!A || !B)
282     return;
283
284   const MCSymbol &SA = A->getSymbol();
285   const MCSymbol &SB = B->getSymbol();
286
287   if (SA.isUndefined() || SB.isUndefined())
288     return;
289
290   if (!Asm->getWriter().IsSymbolRefDifferenceFullyResolved(*Asm, A, B, InSet))
291     return;
292
293   MCSymbolData &AD = Asm->getSymbolData(SA);
294   MCSymbolData &BD = Asm->getSymbolData(SB);
295
296   if (AD.getFragment() == BD.getFragment()) {
297     Addend += (AD.getOffset() - BD.getOffset());
298
299     // Clear the symbol expr pointers to indicate we have folded these
300     // operands.
301     A = B = 0;
302     return;
303   }
304
305   if (!Layout)
306     return;
307
308   const MCSectionData &SecA = *AD.getFragment()->getParent();
309   const MCSectionData &SecB = *BD.getFragment()->getParent();
310
311   if ((&SecA != &SecB) && !Addrs)
312     return;
313
314   // Eagerly evaluate.
315   Addend += (Layout->getSymbolOffset(&Asm->getSymbolData(A->getSymbol())) -
316              Layout->getSymbolOffset(&Asm->getSymbolData(B->getSymbol())));
317   if (Addrs && (&SecA != &SecB))
318     Addend += (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
319
320   // Clear the symbol expr pointers to indicate we have folded these
321   // operands.
322   A = B = 0;
323 }
324
325 /// \brief Evaluate the result of an add between (conceptually) two MCValues.
326 ///
327 /// This routine conceptually attempts to construct an MCValue:
328 ///   Result = (Result_A - Result_B + Result_Cst)
329 /// from two MCValue's LHS and RHS where
330 ///   Result = LHS + RHS
331 /// and
332 ///   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
333 ///
334 /// This routine attempts to aggresively fold the operands such that the result
335 /// is representable in an MCValue, but may not always succeed.
336 ///
337 /// \returns True on success, false if the result is not representable in an
338 /// MCValue.
339
340 /// NOTE: It is really important to have both the Asm and Layout arguments.
341 /// They might look redundant, but this function can be used before layout
342 /// is done (see the object streamer for example) and having the Asm argument
343 /// lets us avoid relaxations early.
344 static bool EvaluateSymbolicAdd(const MCAssembler *Asm,
345                                 const MCAsmLayout *Layout,
346                                 const SectionAddrMap *Addrs,
347                                 bool InSet,
348                                 const MCValue &LHS,const MCSymbolRefExpr *RHS_A,
349                                 const MCSymbolRefExpr *RHS_B, int64_t RHS_Cst,
350                                 MCValue &Res) {
351   // FIXME: This routine (and other evaluation parts) are *incredibly* sloppy
352   // about dealing with modifiers. This will ultimately bite us, one day.
353   const MCSymbolRefExpr *LHS_A = LHS.getSymA();
354   const MCSymbolRefExpr *LHS_B = LHS.getSymB();
355   int64_t LHS_Cst = LHS.getConstant();
356
357   // Fold the result constant immediately.
358   int64_t Result_Cst = LHS_Cst + RHS_Cst;
359
360   assert((!Layout || Asm) &&
361          "Must have an assembler object if layout is given!");
362
363   // If we have a layout, we can fold resolved differences.
364   if (Asm) {
365     // First, fold out any differences which are fully resolved. By
366     // reassociating terms in
367     //   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
368     // we have the four possible differences:
369     //   (LHS_A - LHS_B),
370     //   (LHS_A - RHS_B),
371     //   (RHS_A - LHS_B),
372     //   (RHS_A - RHS_B).
373     // Since we are attempting to be as aggresive as possible about folding, we
374     // attempt to evaluate each possible alternative.
375     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, LHS_B,
376                                         Result_Cst);
377     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, RHS_B,
378                                         Result_Cst);
379     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, LHS_B,
380                                         Result_Cst);
381     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, RHS_B,
382                                         Result_Cst);
383   }
384
385   // We can't represent the addition or subtraction of two symbols.
386   if ((LHS_A && RHS_A) || (LHS_B && RHS_B))
387     return false;
388
389   // At this point, we have at most one additive symbol and one subtractive
390   // symbol -- find them.
391   const MCSymbolRefExpr *A = LHS_A ? LHS_A : RHS_A;
392   const MCSymbolRefExpr *B = LHS_B ? LHS_B : RHS_B;
393
394   // If we have a negated symbol, then we must have also have a non-negated
395   // symbol in order to encode the expression.
396   if (B && !A)
397     return false;
398
399   Res = MCValue::get(A, B, Result_Cst);
400   return true;
401 }
402
403 bool MCExpr::EvaluateAsRelocatable(MCValue &Res,
404                                    const MCAsmLayout &Layout) const {
405   return EvaluateAsRelocatableImpl(Res, &Layout.getAssembler(), &Layout,
406                                    0, false);
407 }
408
409 bool MCExpr::EvaluateAsRelocatableImpl(MCValue &Res,
410                                        const MCAssembler *Asm,
411                                        const MCAsmLayout *Layout,
412                                        const SectionAddrMap *Addrs,
413                                        bool InSet) const {
414   ++stats::MCExprEvaluate;
415
416   switch (getKind()) {
417   case Target:
418     return cast<MCTargetExpr>(this)->EvaluateAsRelocatableImpl(Res, Layout);
419
420   case Constant:
421     Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());
422     return true;
423
424   case SymbolRef: {
425     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
426     const MCSymbol &Sym = SRE->getSymbol();
427
428     // Evaluate recursively if this is a variable.
429     if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None) {
430       bool Ret = Sym.getVariableValue()->EvaluateAsRelocatableImpl(Res, Asm,
431                                                                    Layout,
432                                                                    Addrs,
433                                                                    true);
434       // If we failed to simplify this to a constant, let the target
435       // handle it.
436       if (Ret && !Res.getSymA() && !Res.getSymB())
437         return true;
438     }
439
440     Res = MCValue::get(SRE, 0, 0);
441     return true;
442   }
443
444   case Unary: {
445     const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);
446     MCValue Value;
447
448     if (!AUE->getSubExpr()->EvaluateAsRelocatableImpl(Value, Asm, Layout,
449                                                       Addrs, InSet))
450       return false;
451
452     switch (AUE->getOpcode()) {
453     case MCUnaryExpr::LNot:
454       if (!Value.isAbsolute())
455         return false;
456       Res = MCValue::get(!Value.getConstant());
457       break;
458     case MCUnaryExpr::Minus:
459       /// -(a - b + const) ==> (b - a - const)
460       if (Value.getSymA() && !Value.getSymB())
461         return false;
462       Res = MCValue::get(Value.getSymB(), Value.getSymA(),
463                          -Value.getConstant());
464       break;
465     case MCUnaryExpr::Not:
466       if (!Value.isAbsolute())
467         return false;
468       Res = MCValue::get(~Value.getConstant());
469       break;
470     case MCUnaryExpr::Plus:
471       Res = Value;
472       break;
473     }
474
475     return true;
476   }
477
478   case Binary: {
479     const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);
480     MCValue LHSValue, RHSValue;
481
482     if (!ABE->getLHS()->EvaluateAsRelocatableImpl(LHSValue, Asm, Layout,
483                                                   Addrs, InSet) ||
484         !ABE->getRHS()->EvaluateAsRelocatableImpl(RHSValue, Asm, Layout,
485                                                   Addrs, InSet))
486       return false;
487
488     // We only support a few operations on non-constant expressions, handle
489     // those first.
490     if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {
491       switch (ABE->getOpcode()) {
492       default:
493         return false;
494       case MCBinaryExpr::Sub:
495         // Negate RHS and add.
496         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
497                                    RHSValue.getSymB(), RHSValue.getSymA(),
498                                    -RHSValue.getConstant(),
499                                    Res);
500
501       case MCBinaryExpr::Add:
502         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
503                                    RHSValue.getSymA(), RHSValue.getSymB(),
504                                    RHSValue.getConstant(),
505                                    Res);
506       }
507     }
508
509     // FIXME: We need target hooks for the evaluation. It may be limited in
510     // width, and gas defines the result of comparisons and right shifts
511     // differently from Apple as.
512     int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();
513     int64_t Result = 0;
514     switch (ABE->getOpcode()) {
515     case MCBinaryExpr::Add:  Result = LHS + RHS; break;
516     case MCBinaryExpr::And:  Result = LHS & RHS; break;
517     case MCBinaryExpr::Div:  Result = LHS / RHS; break;
518     case MCBinaryExpr::EQ:   Result = LHS == RHS; break;
519     case MCBinaryExpr::GT:   Result = LHS > RHS; break;
520     case MCBinaryExpr::GTE:  Result = LHS >= RHS; break;
521     case MCBinaryExpr::LAnd: Result = LHS && RHS; break;
522     case MCBinaryExpr::LOr:  Result = LHS || RHS; break;
523     case MCBinaryExpr::LT:   Result = LHS < RHS; break;
524     case MCBinaryExpr::LTE:  Result = LHS <= RHS; break;
525     case MCBinaryExpr::Mod:  Result = LHS % RHS; break;
526     case MCBinaryExpr::Mul:  Result = LHS * RHS; break;
527     case MCBinaryExpr::NE:   Result = LHS != RHS; break;
528     case MCBinaryExpr::Or:   Result = LHS | RHS; break;
529     case MCBinaryExpr::Shl:  Result = LHS << RHS; break;
530     case MCBinaryExpr::Shr:  Result = LHS >> RHS; break;
531     case MCBinaryExpr::Sub:  Result = LHS - RHS; break;
532     case MCBinaryExpr::Xor:  Result = LHS ^ RHS; break;
533     }
534
535     Res = MCValue::get(Result);
536     return true;
537   }
538   }
539
540   assert(0 && "Invalid assembly expression kind!");
541   return false;
542 }