Reorder some functions and add comments. No functionality change.
[oota-llvm.git] / lib / IR / Attributes.cpp
1 //===-- Attributes.cpp - Implement AttributesList -------------------------===//
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 // \file
11 // \brief This file implements the Attribute, AttributeImpl, AttrBuilder,
12 // AttributeSetImpl, and AttributeSet classes.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/IR/Attributes.h"
17 #include "AttributeImpl.h"
18 #include "LLVMContextImpl.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/IR/Type.h"
22 #include "llvm/Support/Atomic.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 using namespace llvm;
29
30 //===----------------------------------------------------------------------===//
31 // Attribute Implementation
32 //===----------------------------------------------------------------------===//
33
34 Attribute Attribute::get(LLVMContext &Context, AttrKind Kind) {
35   AttrBuilder B;
36   return Attribute::get(Context, B.addAttribute(Kind));
37 }
38
39 Attribute Attribute::get(LLVMContext &Context, AttrBuilder &B) {
40   // If there are no attributes, return an empty Attribute class.
41   if (!B.hasAttributes())
42     return Attribute();
43
44   // Otherwise, build a key to look up the existing attributes.
45   LLVMContextImpl *pImpl = Context.pImpl;
46   FoldingSetNodeID ID;
47   ConstantInt *CI = ConstantInt::get(Type::getInt64Ty(Context), B.Raw());
48   ID.AddPointer(CI);
49
50   void *InsertPoint;
51   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
52
53   if (!PA) {
54     // If we didn't find any existing attributes of the same shape then create a
55     // new one and insert it.
56     PA = new AttributeImpl(Context, CI);
57     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
58   }
59
60   // Return the AttributesList that we found or created.
61   return Attribute(PA);
62 }
63
64 Attribute Attribute::getWithAlignment(LLVMContext &Context, uint64_t Align) {
65   AttrBuilder B;
66   return get(Context, B.addAlignmentAttr(Align));
67 }
68
69 Attribute Attribute::getWithStackAlignment(LLVMContext &Context,
70                                            uint64_t Align) {
71   AttrBuilder B;
72   return get(Context, B.addStackAlignmentAttr(Align));
73 }
74
75 bool Attribute::hasAttribute(AttrKind Val) const {
76   return pImpl && pImpl->hasAttribute(Val);
77 }
78
79 bool Attribute::hasAttributes() const {
80   return pImpl && pImpl->hasAttributes();
81 }
82
83 /// This returns the alignment field of an attribute as a byte alignment value.
84 unsigned Attribute::getAlignment() const {
85   if (!hasAttribute(Attribute::Alignment))
86     return 0;
87   return pImpl->getAlignment();
88 }
89
90 /// This returns the stack alignment field of an attribute as a byte alignment
91 /// value.
92 unsigned Attribute::getStackAlignment() const {
93   if (!hasAttribute(Attribute::StackAlignment))
94     return 0;
95   return pImpl->getStackAlignment();
96 }
97
98 std::string Attribute::getAsString() const {
99   std::string Result;
100   if (hasAttribute(Attribute::ZExt))
101     Result += "zeroext ";
102   if (hasAttribute(Attribute::SExt))
103     Result += "signext ";
104   if (hasAttribute(Attribute::NoReturn))
105     Result += "noreturn ";
106   if (hasAttribute(Attribute::NoUnwind))
107     Result += "nounwind ";
108   if (hasAttribute(Attribute::UWTable))
109     Result += "uwtable ";
110   if (hasAttribute(Attribute::ReturnsTwice))
111     Result += "returns_twice ";
112   if (hasAttribute(Attribute::InReg))
113     Result += "inreg ";
114   if (hasAttribute(Attribute::NoAlias))
115     Result += "noalias ";
116   if (hasAttribute(Attribute::NoCapture))
117     Result += "nocapture ";
118   if (hasAttribute(Attribute::StructRet))
119     Result += "sret ";
120   if (hasAttribute(Attribute::ByVal))
121     Result += "byval ";
122   if (hasAttribute(Attribute::Nest))
123     Result += "nest ";
124   if (hasAttribute(Attribute::ReadNone))
125     Result += "readnone ";
126   if (hasAttribute(Attribute::ReadOnly))
127     Result += "readonly ";
128   if (hasAttribute(Attribute::OptimizeForSize))
129     Result += "optsize ";
130   if (hasAttribute(Attribute::NoInline))
131     Result += "noinline ";
132   if (hasAttribute(Attribute::InlineHint))
133     Result += "inlinehint ";
134   if (hasAttribute(Attribute::AlwaysInline))
135     Result += "alwaysinline ";
136   if (hasAttribute(Attribute::StackProtect))
137     Result += "ssp ";
138   if (hasAttribute(Attribute::StackProtectReq))
139     Result += "sspreq ";
140   if (hasAttribute(Attribute::StackProtectStrong))
141     Result += "sspstrong ";
142   if (hasAttribute(Attribute::NoRedZone))
143     Result += "noredzone ";
144   if (hasAttribute(Attribute::NoImplicitFloat))
145     Result += "noimplicitfloat ";
146   if (hasAttribute(Attribute::Naked))
147     Result += "naked ";
148   if (hasAttribute(Attribute::NonLazyBind))
149     Result += "nonlazybind ";
150   if (hasAttribute(Attribute::AddressSafety))
151     Result += "address_safety ";
152   if (hasAttribute(Attribute::MinSize))
153     Result += "minsize ";
154   if (hasAttribute(Attribute::StackAlignment)) {
155     Result += "alignstack(";
156     Result += utostr(getStackAlignment());
157     Result += ") ";
158   }
159   if (hasAttribute(Attribute::Alignment)) {
160     Result += "align ";
161     Result += utostr(getAlignment());
162     Result += " ";
163   }
164   if (hasAttribute(Attribute::NoDuplicate))
165     Result += "noduplicate ";
166   // Trim the trailing space.
167   assert(!Result.empty() && "Unknown attribute!");
168   Result.erase(Result.end()-1);
169   return Result;
170 }
171
172 bool Attribute::operator==(AttrKind K) const {
173   return pImpl && *pImpl == K;
174 }
175 bool Attribute::operator!=(AttrKind K) const {
176   return !(*this == K);
177 }
178
179 bool Attribute::operator<(Attribute A) const {
180   if (!pImpl && !A.pImpl) return false;
181   if (!pImpl) return true;
182   if (!A.pImpl) return false;
183   return *pImpl < *A.pImpl;
184 }
185
186 uint64_t Attribute::Raw() const {
187   return pImpl ? pImpl->Raw() : 0;
188 }
189
190 //===----------------------------------------------------------------------===//
191 // AttributeImpl Definition
192 //===----------------------------------------------------------------------===//
193
194 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind data)
195   : Context(C) {
196   Data = ConstantInt::get(Type::getInt64Ty(C), data);
197 }
198 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind data,
199                              ArrayRef<Constant*> values)
200   : Context(C) {
201   Data = ConstantInt::get(Type::getInt64Ty(C), data);
202   Vals.reserve(values.size());
203   Vals.append(values.begin(), values.end());
204 }
205 AttributeImpl::AttributeImpl(LLVMContext &C, StringRef data)
206   : Context(C) {
207   Data = ConstantDataArray::getString(C, data);
208 }
209
210 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
211   return (Raw() & getAttrMask(A)) != 0;
212 }
213
214 bool AttributeImpl::hasAttributes() const {
215   return Raw() != 0;
216 }
217
218 uint64_t AttributeImpl::getAlignment() const {
219   uint64_t Mask = Raw() & getAttrMask(Attribute::Alignment);
220   return 1ULL << ((Mask >> 16) - 1);
221 }
222
223 uint64_t AttributeImpl::getStackAlignment() const {
224   uint64_t Mask = Raw() & getAttrMask(Attribute::StackAlignment);
225   return 1ULL << ((Mask >> 26) - 1);
226 }
227
228 bool AttributeImpl::operator==(Attribute::AttrKind Kind) const {
229   if (ConstantInt *CI = dyn_cast<ConstantInt>(Data))
230     return CI->getZExtValue() == Kind;
231   return false;
232 }
233 bool AttributeImpl::operator!=(Attribute::AttrKind Kind) const {
234   return !(*this == Kind);
235 }
236
237 bool AttributeImpl::operator==(StringRef Kind) const {
238   if (ConstantDataArray *CDA = dyn_cast<ConstantDataArray>(Data))
239     if (CDA->isString())
240       return CDA->getAsString() == Kind;
241   return false;
242 }
243
244 bool AttributeImpl::operator!=(StringRef Kind) const {
245   return !(*this == Kind);
246 }
247
248 bool AttributeImpl::operator<(const AttributeImpl &AI) const {
249   if (!Data && !AI.Data) return false;
250   if (!Data && AI.Data) return true;
251   if (Data && !AI.Data) return false;
252
253   ConstantInt *ThisCI = dyn_cast<ConstantInt>(Data);
254   ConstantInt *ThatCI = dyn_cast<ConstantInt>(AI.Data);
255
256   ConstantDataArray *ThisCDA = dyn_cast<ConstantDataArray>(Data);
257   ConstantDataArray *ThatCDA = dyn_cast<ConstantDataArray>(AI.Data);
258
259   if (ThisCI && ThatCI)
260     return ThisCI->getZExtValue() < ThatCI->getZExtValue();
261
262   if (ThisCI && ThatCDA)
263     return true;
264
265   if (ThisCDA && ThatCI)
266     return false;
267
268   return ThisCDA->getAsString() < ThatCDA->getAsString();
269 }
270
271 uint64_t AttributeImpl::Raw() const {
272   // FIXME: Remove this.
273   return cast<ConstantInt>(Data)->getZExtValue();
274 }
275
276 uint64_t AttributeImpl::getAttrMask(Attribute::AttrKind Val) {
277   // FIXME: Remove this.
278   switch (Val) {
279   case Attribute::EndAttrKinds:
280   case Attribute::AttrKindEmptyKey:
281   case Attribute::AttrKindTombstoneKey:
282     llvm_unreachable("Synthetic enumerators which should never get here");
283
284   case Attribute::None:            return 0;
285   case Attribute::ZExt:            return 1 << 0;
286   case Attribute::SExt:            return 1 << 1;
287   case Attribute::NoReturn:        return 1 << 2;
288   case Attribute::InReg:           return 1 << 3;
289   case Attribute::StructRet:       return 1 << 4;
290   case Attribute::NoUnwind:        return 1 << 5;
291   case Attribute::NoAlias:         return 1 << 6;
292   case Attribute::ByVal:           return 1 << 7;
293   case Attribute::Nest:            return 1 << 8;
294   case Attribute::ReadNone:        return 1 << 9;
295   case Attribute::ReadOnly:        return 1 << 10;
296   case Attribute::NoInline:        return 1 << 11;
297   case Attribute::AlwaysInline:    return 1 << 12;
298   case Attribute::OptimizeForSize: return 1 << 13;
299   case Attribute::StackProtect:    return 1 << 14;
300   case Attribute::StackProtectReq: return 1 << 15;
301   case Attribute::Alignment:       return 31 << 16;
302   case Attribute::NoCapture:       return 1 << 21;
303   case Attribute::NoRedZone:       return 1 << 22;
304   case Attribute::NoImplicitFloat: return 1 << 23;
305   case Attribute::Naked:           return 1 << 24;
306   case Attribute::InlineHint:      return 1 << 25;
307   case Attribute::StackAlignment:  return 7 << 26;
308   case Attribute::ReturnsTwice:    return 1 << 29;
309   case Attribute::UWTable:         return 1 << 30;
310   case Attribute::NonLazyBind:     return 1U << 31;
311   case Attribute::AddressSafety:   return 1ULL << 32;
312   case Attribute::MinSize:         return 1ULL << 33;
313   case Attribute::NoDuplicate:     return 1ULL << 34;
314   case Attribute::StackProtectStrong: return 1ULL << 35;
315   }
316   llvm_unreachable("Unsupported attribute type");
317 }
318
319 //===----------------------------------------------------------------------===//
320 // AttributeSetNode Definition
321 //===----------------------------------------------------------------------===//
322
323 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
324                                         ArrayRef<Attribute> Attrs) {
325   if (Attrs.empty())
326     return 0;
327
328   // Otherwise, build a key to look up the existing attributes.
329   LLVMContextImpl *pImpl = C.pImpl;
330   FoldingSetNodeID ID;
331
332   SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
333   std::sort(SortedAttrs.begin(), SortedAttrs.end());
334
335   for (SmallVectorImpl<Attribute>::iterator I = SortedAttrs.begin(),
336          E = SortedAttrs.end(); I != E; ++I)
337     I->Profile(ID);
338
339   void *InsertPoint;
340   AttributeSetNode *PA =
341     pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
342
343   // If we didn't find any existing attributes of the same shape then create a
344   // new one and insert it.
345   if (!PA) {
346     PA = new AttributeSetNode(SortedAttrs);
347     pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
348   }
349
350   // Return the AttributesListNode that we found or created.
351   return PA;
352 }
353
354 //===----------------------------------------------------------------------===//
355 // AttributeSetImpl Definition
356 //===----------------------------------------------------------------------===//
357
358 uint64_t AttributeSetImpl::Raw(uint64_t Index) const {
359   for (unsigned I = 0, E = getNumAttributes(); I != E; ++I) {
360     if (getSlotIndex(I) != Index) continue;
361     const AttributeSetNode *ASN = AttrNodes[I].second;
362     AttrBuilder B;
363
364     for (AttributeSetNode::const_iterator II = ASN->begin(),
365            IE = ASN->end(); II != IE; ++II)
366       B.addAttributes(*II);
367     return B.Raw();
368   }
369
370   return 0;
371 }
372
373 //===----------------------------------------------------------------------===//
374 // AttributeSet Construction and Mutation Methods
375 //===----------------------------------------------------------------------===//
376
377 AttributeSet AttributeSet::getImpl(LLVMContext &C,
378                                    ArrayRef<std::pair<unsigned,
379                                                    AttributeSetNode*> > Attrs) {
380   LLVMContextImpl *pImpl = C.pImpl;
381   FoldingSetNodeID ID;
382   AttributeSetImpl::Profile(ID, Attrs);
383
384   void *InsertPoint;
385   AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
386
387   // If we didn't find any existing attributes of the same shape then
388   // create a new one and insert it.
389   if (!PA) {
390     PA = new AttributeSetImpl(C, Attrs);
391     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
392   }
393
394   // Return the AttributesList that we found or created.
395   return AttributeSet(PA);
396 }
397
398 AttributeSet AttributeSet::get(LLVMContext &C,
399                                ArrayRef<std::pair<unsigned, Attribute> > Attrs){
400   // If there are no attributes then return a null AttributesList pointer.
401   if (Attrs.empty())
402     return AttributeSet();
403
404 #ifndef NDEBUG
405   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
406     assert((!i || Attrs[i-1].first <= Attrs[i].first) &&
407            "Misordered Attributes list!");
408     assert(Attrs[i].second.hasAttributes() &&
409            "Pointless attribute!");
410   }
411 #endif
412
413   // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
414   // list.
415   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrPairVec;
416   for (ArrayRef<std::pair<unsigned, Attribute> >::iterator I = Attrs.begin(),
417          E = Attrs.end(); I != E; ) {
418     unsigned Index = I->first;
419     SmallVector<Attribute, 4> AttrVec;
420     while (I->first == Index && I != E) {
421       AttrVec.push_back(I->second);
422       ++I;
423     }
424
425     AttrPairVec.push_back(std::make_pair(Index,
426                                          AttributeSetNode::get(C, AttrVec)));
427   }
428
429   return getImpl(C, AttrPairVec);
430 }
431
432 AttributeSet AttributeSet::get(LLVMContext &C,
433                                ArrayRef<std::pair<unsigned,
434                                                   AttributeSetNode*> > Attrs) {
435   // If there are no attributes then return a null AttributesList pointer.
436   if (Attrs.empty())
437     return AttributeSet();
438
439   return getImpl(C, Attrs);
440 }
441
442 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx, AttrBuilder &B) {
443   if (!B.hasAttributes())
444     return AttributeSet();
445   return get(C, ArrayRef<std::pair<unsigned, Attribute> >(
446                std::make_pair(Idx, Attribute::get(C, B))));
447 }
448
449 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx,
450                                ArrayRef<Attribute::AttrKind> Kind) {
451   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
452   for (ArrayRef<Attribute::AttrKind>::iterator I = Kind.begin(),
453          E = Kind.end(); I != E; ++I)
454     Attrs.push_back(std::make_pair(Idx, Attribute::get(C, *I)));
455   return get(C, Attrs);
456 }
457
458 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<AttributeSet> Attrs) {
459   if (Attrs.empty()) return AttributeSet();
460
461   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrNodeVec;
462   for (unsigned I = 0, E = Attrs.size(); I != E; ++I) {
463     AttributeSet AS = Attrs[I];
464     if (!AS.pImpl) continue;
465     AttrNodeVec.append(AS.pImpl->AttrNodes.begin(), AS.pImpl->AttrNodes.end());
466   }
467
468   return getImpl(C, AttrNodeVec);
469 }
470
471 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Idx,
472                                         Attribute::AttrKind Attr) const {
473   return addAttributes(C, Idx, AttributeSet::get(C, Idx, Attr));
474 }
475
476 AttributeSet AttributeSet::addAttributes(LLVMContext &C, unsigned Idx,
477                                          AttributeSet Attrs) const {
478   if (!pImpl) return Attrs;
479   if (!Attrs.pImpl) return *this;
480
481 #ifndef NDEBUG
482   // FIXME it is not obvious how this should work for alignment. For now, say
483   // we can't change a known alignment.
484   unsigned OldAlign = getParamAlignment(Idx);
485   unsigned NewAlign = Attrs.getParamAlignment(Idx);
486   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
487          "Attempt to change alignment!");
488 #endif
489
490   // Add the attribute slots before the one we're trying to add.
491   SmallVector<AttributeSet, 4> AttrSet;
492   uint64_t NumAttrs = pImpl->getNumAttributes();
493   AttributeSet AS;
494   uint64_t LastIndex = 0;
495   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
496     if (getSlotIndex(I) >= Idx) {
497       if (getSlotIndex(I) == Idx) AS = getSlotAttributes(LastIndex++);
498       break;
499     }
500     LastIndex = I + 1;
501     AttrSet.push_back(getSlotAttributes(I));
502   }
503
504   // Now add the attribute into the correct slot. There may already be an
505   // AttributeSet there.
506   AttrBuilder B(AS, Idx);
507
508   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
509     if (Attrs.getSlotIndex(I) == Idx) {
510       for (AttributeSetImpl::const_iterator II = Attrs.pImpl->begin(I),
511              IE = Attrs.pImpl->end(I); II != IE; ++II)
512         B.addAttributes(*II);
513       break;
514     }
515
516   AttrSet.push_back(AttributeSet::get(C, Idx, B));
517
518   // Add the remaining attribute slots.
519   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
520     AttrSet.push_back(getSlotAttributes(I));
521
522   return get(C, AttrSet);
523 }
524
525 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, unsigned Idx,
526                                            Attribute::AttrKind Attr) const {
527   return removeAttributes(C, Idx, AttributeSet::get(C, Idx, Attr));
528 }
529
530 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Idx,
531                                             AttributeSet Attrs) const {
532   if (!pImpl) return AttributeSet();
533   if (!Attrs.pImpl) return *this;
534
535 #ifndef NDEBUG
536   // FIXME it is not obvious how this should work for alignment.
537   // For now, say we can't pass in alignment, which no current use does.
538   assert(!Attrs.hasAttribute(Idx, Attribute::Alignment) &&
539          "Attempt to change alignment!");
540 #endif
541
542   // Add the attribute slots before the one we're trying to add.
543   SmallVector<AttributeSet, 4> AttrSet;
544   uint64_t NumAttrs = pImpl->getNumAttributes();
545   AttributeSet AS;
546   uint64_t LastIndex = 0;
547   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
548     if (getSlotIndex(I) >= Idx) {
549       if (getSlotIndex(I) == Idx) AS = getSlotAttributes(LastIndex++);
550       break;
551     }
552     LastIndex = I + 1;
553     AttrSet.push_back(getSlotAttributes(I));
554   }
555
556   // Now add the attribute into the correct slot. There may already be an
557   // AttributeSet there.
558   AttrBuilder B(AS, Idx);
559
560   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
561     if (Attrs.getSlotIndex(I) == Idx) {
562       for (AttributeSetImpl::const_iterator II = Attrs.pImpl->begin(I),
563              IE = Attrs.pImpl->end(I); II != IE; ++II)
564         B.removeAttributes(*II);
565       break;
566     }
567
568   AttrSet.push_back(AttributeSet::get(C, Idx, B));
569
570   // Add the remaining attribute slots.
571   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
572     AttrSet.push_back(getSlotAttributes(I));
573
574   return get(C, AttrSet);
575 }
576
577 //===----------------------------------------------------------------------===//
578 // AttributeSet Accessor Methods
579 //===----------------------------------------------------------------------===//
580
581 AttributeSet AttributeSet::getParamAttributes(unsigned Idx) const {
582   return pImpl && hasAttributes(Idx) ?
583     AttributeSet::get(pImpl->getContext(),
584                       ArrayRef<std::pair<unsigned, Attribute> >(
585                         std::make_pair(Idx, getAttributes(Idx)))) :
586     AttributeSet();
587 }
588
589 AttributeSet AttributeSet::getRetAttributes() const {
590   return pImpl && hasAttributes(ReturnIndex) ?
591     AttributeSet::get(pImpl->getContext(),
592                       ArrayRef<std::pair<unsigned, Attribute> >(
593                         std::make_pair(ReturnIndex,
594                                        getAttributes(ReturnIndex)))) :
595     AttributeSet();
596 }
597
598 AttributeSet AttributeSet::getFnAttributes() const {
599   return pImpl && hasAttributes(FunctionIndex) ?
600     AttributeSet::get(pImpl->getContext(),
601                       ArrayRef<std::pair<unsigned, Attribute> >(
602                         std::make_pair(FunctionIndex,
603                                        getAttributes(FunctionIndex)))) :
604     AttributeSet();
605 }
606
607 bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
608   return getAttributes(Index).hasAttribute(Kind);
609 }
610
611 bool AttributeSet::hasAttributes(unsigned Index) const {
612   return getAttributes(Index).hasAttributes();
613 }
614
615 /// \brief Return true if the specified attribute is set for at least one
616 /// parameter or for the return value.
617 bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
618   if (pImpl == 0) return false;
619
620   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
621     for (AttributeSetImpl::const_iterator II = pImpl->begin(I),
622            IE = pImpl->end(I); II != IE; ++II)
623       if (II->hasAttribute(Attr))
624         return true;
625
626   return false;
627 }
628
629 unsigned AttributeSet::getParamAlignment(unsigned Idx) const {
630   return getAttributes(Idx).getAlignment();
631 }
632
633 unsigned AttributeSet::getStackAlignment(unsigned Index) const {
634   return getAttributes(Index).getStackAlignment();
635 }
636
637 std::string AttributeSet::getAsString(unsigned Index) const {
638   return getAttributes(Index).getAsString();
639 }
640
641 /// \brief The attributes for the specified index are returned.
642 ///
643 /// FIXME: This shouldn't return 'Attribute'.
644 Attribute AttributeSet::getAttributes(unsigned Idx) const {
645   if (pImpl == 0) return Attribute();
646
647   // Loop through to find the attribute we want.
648   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I) {
649     if (pImpl->getSlotIndex(I) != Idx) continue;
650
651     AttrBuilder B;
652     for (AttributeSetImpl::const_iterator II = pImpl->begin(I),
653            IE = pImpl->end(I); II != IE; ++II)
654       B.addAttributes(*II);
655     return Attribute::get(pImpl->getContext(), B);
656   }
657
658   return Attribute();
659 }
660
661 //===----------------------------------------------------------------------===//
662 // AttributeSet Introspection Methods
663 //===----------------------------------------------------------------------===//
664
665 /// \brief Return the number of slots used in this attribute list.  This is the
666 /// number of arguments that have an attribute set on them (including the
667 /// function itself).
668 unsigned AttributeSet::getNumSlots() const {
669   return pImpl ? pImpl->getNumAttributes() : 0;
670 }
671
672 uint64_t AttributeSet::getSlotIndex(unsigned Slot) const {
673   assert(pImpl && Slot < pImpl->getNumAttributes() &&
674          "Slot # out of range!");
675   return pImpl->getSlotIndex(Slot);
676 }
677
678 AttributeSet AttributeSet::getSlotAttributes(unsigned Slot) const {
679   assert(pImpl && Slot < pImpl->getNumAttributes() &&
680          "Slot # out of range!");
681   return pImpl->getSlotAttributes(Slot);
682 }
683
684 uint64_t AttributeSet::Raw(unsigned Index) const {
685   // FIXME: Remove this.
686   return pImpl ? pImpl->Raw(Index) : 0;
687 }
688
689 void AttributeSet::dump() const {
690   dbgs() << "PAL[\n";
691
692   for (unsigned i = 0, e = getNumSlots(); i < e; ++i) {
693     uint64_t Index = getSlotIndex(i);
694     dbgs() << "  { ";
695     if (Index == ~0U)
696       dbgs() << "~0U";
697     else
698       dbgs() << Index;
699     dbgs() << " => " << getAsString(Index) << " }\n";
700   }
701
702   dbgs() << "]\n";
703 }
704
705 //===----------------------------------------------------------------------===//
706 // AttrBuilder Method Implementations
707 //===----------------------------------------------------------------------===//
708
709 AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Idx)
710   : Alignment(0), StackAlignment(0) {
711   AttributeSetImpl *pImpl = AS.pImpl;
712   if (!pImpl) return;
713
714   AttrBuilder B;
715
716   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I) {
717     if (pImpl->getSlotIndex(I) != Idx) continue;
718
719     for (AttributeSetNode::const_iterator II = pImpl->begin(I),
720            IE = pImpl->end(I); II != IE; ++II)
721       B.addAttributes(*II);
722
723     break;
724   }
725
726   if (!B.hasAttributes()) return;
727
728   uint64_t Mask = B.Raw();
729
730   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
731        I = Attribute::AttrKind(I + 1)) {
732     if (uint64_t A = (Mask & AttributeImpl::getAttrMask(I))) {
733       Attrs.insert(I);
734
735       if (I == Attribute::Alignment)
736         Alignment = 1ULL << ((A >> 16) - 1);
737       else if (I == Attribute::StackAlignment)
738         StackAlignment = 1ULL << ((A >> 26)-1);
739     }
740   }
741 }
742
743 void AttrBuilder::clear() {
744   Attrs.clear();
745   Alignment = StackAlignment = 0;
746 }
747
748 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
749   Attrs.insert(Val);
750   return *this;
751 }
752
753 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
754   Attrs.erase(Val);
755   if (Val == Attribute::Alignment)
756     Alignment = 0;
757   else if (Val == Attribute::StackAlignment)
758     StackAlignment = 0;
759
760   return *this;
761 }
762
763 AttrBuilder &AttrBuilder::addAttributes(Attribute Attr) {
764   uint64_t Mask = Attr.Raw();
765
766   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
767        I = Attribute::AttrKind(I + 1))
768     if ((Mask & AttributeImpl::getAttrMask(I)) != 0)
769       Attrs.insert(I);
770
771   if (Attr.getAlignment())
772     Alignment = Attr.getAlignment();
773   if (Attr.getStackAlignment())
774     StackAlignment = Attr.getStackAlignment();
775   return *this;
776 }
777
778 AttrBuilder &AttrBuilder::removeAttributes(Attribute A) {
779   uint64_t Mask = A.Raw();
780
781   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
782        I = Attribute::AttrKind(I + 1)) {
783     if (Mask & AttributeImpl::getAttrMask(I)) {
784       Attrs.erase(I);
785
786       if (I == Attribute::Alignment)
787         Alignment = 0;
788       else if (I == Attribute::StackAlignment)
789         StackAlignment = 0;
790     }
791   }
792
793   return *this;
794 }
795
796 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
797   if (Align == 0) return *this;
798
799   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
800   assert(Align <= 0x40000000 && "Alignment too large.");
801
802   Attrs.insert(Attribute::Alignment);
803   Alignment = Align;
804   return *this;
805 }
806
807 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
808   // Default alignment, allow the target to define how to align it.
809   if (Align == 0) return *this;
810
811   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
812   assert(Align <= 0x100 && "Alignment too large.");
813
814   Attrs.insert(Attribute::StackAlignment);
815   StackAlignment = Align;
816   return *this;
817 }
818
819 bool AttrBuilder::contains(Attribute::AttrKind A) const {
820   return Attrs.count(A);
821 }
822
823 bool AttrBuilder::hasAttributes() const {
824   return !Attrs.empty();
825 }
826
827 bool AttrBuilder::hasAttributes(const Attribute &A) const {
828   return Raw() & A.Raw();
829 }
830
831 bool AttrBuilder::hasAlignmentAttr() const {
832   return Alignment != 0;
833 }
834
835 bool AttrBuilder::operator==(const AttrBuilder &B) {
836   SmallVector<Attribute::AttrKind, 8> This(Attrs.begin(), Attrs.end());
837   SmallVector<Attribute::AttrKind, 8> That(B.Attrs.begin(), B.Attrs.end());
838   return This == That;
839 }
840
841 AttrBuilder &AttrBuilder::addRawValue(uint64_t Val) {
842   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
843        I = Attribute::AttrKind(I + 1)) {
844     if (uint64_t A = (Val & AttributeImpl::getAttrMask(I))) {
845       Attrs.insert(I);
846  
847       if (I == Attribute::Alignment)
848         Alignment = 1ULL << ((A >> 16) - 1);
849       else if (I == Attribute::StackAlignment)
850         StackAlignment = 1ULL << ((A >> 26)-1);
851     }
852   }
853  
854   return *this;
855 }
856
857 uint64_t AttrBuilder::Raw() const {
858   uint64_t Mask = 0;
859
860   for (DenseSet<Attribute::AttrKind>::const_iterator I = Attrs.begin(),
861          E = Attrs.end(); I != E; ++I) {
862     Attribute::AttrKind Kind = *I;
863
864     if (Kind == Attribute::Alignment)
865       Mask |= (Log2_32(Alignment) + 1) << 16;
866     else if (Kind == Attribute::StackAlignment)
867       Mask |= (Log2_32(StackAlignment) + 1) << 26;
868     else
869       Mask |= AttributeImpl::getAttrMask(Kind);
870   }
871
872   return Mask;
873 }
874
875 //===----------------------------------------------------------------------===//
876 // AttributeFuncs Function Defintions
877 //===----------------------------------------------------------------------===//
878
879 Attribute AttributeFuncs::typeIncompatible(Type *Ty) {
880   AttrBuilder Incompatible;
881
882   if (!Ty->isIntegerTy())
883     // Attribute that only apply to integers.
884     Incompatible.addAttribute(Attribute::SExt)
885       .addAttribute(Attribute::ZExt);
886
887   if (!Ty->isPointerTy())
888     // Attribute that only apply to pointers.
889     Incompatible.addAttribute(Attribute::ByVal)
890       .addAttribute(Attribute::Nest)
891       .addAttribute(Attribute::NoAlias)
892       .addAttribute(Attribute::NoCapture)
893       .addAttribute(Attribute::StructRet);
894
895   return Attribute::get(Ty->getContext(), Incompatible);
896 }
897
898 /// \brief This returns an integer containing an encoding of all the LLVM
899 /// attributes found in the given attribute bitset.  Any change to this encoding
900 /// is a breaking change to bitcode compatibility.
901 uint64_t AttributeFuncs::encodeLLVMAttributesForBitcode(AttributeSet Attrs,
902                                                         unsigned Index) {
903   // FIXME: It doesn't make sense to store the alignment information as an
904   // expanded out value, we should store it as a log2 value.  However, we can't
905   // just change that here without breaking bitcode compatibility.  If this ever
906   // becomes a problem in practice, we should introduce new tag numbers in the
907   // bitcode file and have those tags use a more efficiently encoded alignment
908   // field.
909
910   // Store the alignment in the bitcode as a 16-bit raw value instead of a 5-bit
911   // log2 encoded value. Shift the bits above the alignment up by 11 bits.
912   uint64_t EncodedAttrs = Attrs.Raw(Index) & 0xffff;
913   if (Attrs.hasAttribute(Index, Attribute::Alignment))
914     EncodedAttrs |= Attrs.getParamAlignment(Index) << 16;
915   EncodedAttrs |= (Attrs.Raw(Index) & (0xffffULL << 21)) << 11;
916   return EncodedAttrs;
917 }
918
919 /// \brief This returns an attribute bitset containing the LLVM attributes that
920 /// have been decoded from the given integer.  This function must stay in sync
921 /// with 'encodeLLVMAttributesForBitcode'.
922 Attribute AttributeFuncs::decodeLLVMAttributesForBitcode(LLVMContext &C,
923                                                          uint64_t EncodedAttrs){
924   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
925   // the bits above 31 down by 11 bits.
926   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
927   assert((!Alignment || isPowerOf2_32(Alignment)) &&
928          "Alignment must be a power of two.");
929
930   AttrBuilder B(EncodedAttrs & 0xffff);
931   if (Alignment)
932     B.addAlignmentAttr(Alignment);
933   B.addRawValue((EncodedAttrs & (0xffffULL << 32)) >> 11);
934   return Attribute::get(C, B);
935 }
936